LeetCode - Problems - Algorithms - 733. Flood Fill
Problem Description
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 perform a flood fill on the image starting from the pixel image[sr][sc].
To perform a flood fill:
Begin with the starting pixel and change its color to color.
Perform the same process for each pixel that is directly adjacent (pixels that share a side with the original pixel, either horizontally or vertically) and shares the same color as the starting pixel.
Keep repeating this process by checking neighboring pixels of the updated pixels and modifying their color if it matches the original color of the starting pixel.
The process stops when there are no more adjacent pixels of the original color to update.
Return the modified image after performing the flood fill.
Example:
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Constraints:
m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], color < 216
0 <= sr < m
0 <= sc < n
My Solution (C#)
public int[][] FloodFill(int[][] image, int sr, int sc, int color)
{
int originalColor = image[sr][sc]; //제일 처음 컬러 저장
//if (originalColor == newColor) { return image; } //같으면 실행할 필요X
Fill(image, sr, sc, originalColor, color); //오리지널컬러 저장해서 넘김
return image;
}
public int[][] Fill(int[][] image, int sr, int sc, int originalColor, int newColor)
{
if (image[sr][sc] == newColor) { return image; } //같으면 실행할 필요 X
if (image[sr][sc] == originalColor)
{
image[sr][sc] = newColor;
//Up 현재 제일 상단이 아니면 실행.
if (sr > 0)
Fill(image, sr - 1, sc, originalColor, newColor);
//Down 현재 제일 아랫단이 아니면 실행.
if (image.Length > sr + 1)
Fill(image, sr + 1, sc, originalColor, newColor);
//Right 제일 왼쪽열이 아닐 경우 실행.
if (sc > 0)
Fill(image, sr, sc - 1, originalColor, newColor);
//Lest 제일 오른쪽 열이 아닐 경우 실행.
if (image[sr].Length > sc + 1)
Fill(image, sr, sc + 1, originalColor, newColor);
}
return image;
}
이해 자체가 어려워서 이해하는 부분만 유튜브에서 확인했다.
이해되고 나서는 originalColor를 받는 재귀함수 Fill()을 만들어서 진행했다.
지금 리뷰하면서 고치고 싶은 부분이 있는데..
newColor와 같은지 체크는 Fill() 안에서 할 필요 없는 것 같다. 주석 처리한 부분에만 하면 될 듯. 중복되서 지웠는데 잘 못 지운 듯?
배열 범위 체크는 Fill 실행하기 직전에 증감이 있는 부분만 체크해줬다. 전체적으로 해줘도 괜찮았겠지만, 뭔가 헷갈림...
'Problem solving > Algorithms' 카테고리의 다른 글
[LeetCode] 300. Longest Increasing Subsequence (2) | 2025.07.12 |
---|---|
[프로그래머스]최댓값과 최솟값 (C#) (0) | 2025.07.11 |
[프로그래머스]약수의 합 (C#) (1) | 2025.07.08 |
[LeetCode] 202. Happy Number(C#) (0) | 2024.01.19 |
[LeetCode] 338. Counting Bits (C#) (1) | 2024.01.13 |