본문 바로가기
Problem Solving/LeetCode

[LeetCode] 733. Flood Fill - Java

by graycode 2026. 10. 6.

• 문제 링크

 

Flood Fill - LeetCode

Can you solve this real interview question? Flood Fill - You are given an image represented by an m x n grid of integers image, where image[i][j] represents the pixel value of the image. You are also given three integers sr, sc, and color. Your task is to

leetcode.com

 

• 풀이 코드

public class Solution {

    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int cur = image[sr][sc];
        if (cur != color) dfs(image, sr, sc, cur, color);

        return image;
    }

    private void dfs(int[][] image, int r, int c, int cur, int tgt) {
        if (r < 0 || r >= image.length || c < 0 || c >= image[0].length || image[r][c] != cur) return;
        image[r][c] = tgt;

        dfs(image, r - 1, c, cur, tgt);
        dfs(image, r + 1, c, cur, tgt);
        dfs(image, r, c - 1, cur, tgt);
        dfs(image, r, c + 1, cur, tgt);
    }

}

댓글