Algorithm/문제 풀이

LeetCode - FloodFile

개발자-H 2021. 8. 7. 17:00

https://leetcode.com/problems/flood-fill/solution/

 

Flood Fill - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

  • 그래프 탐색 문제이다.
  • 경로 탐색 조건에 픽셀 비교 구문을 추가하면 쉽게 해결 할 수 있다.

 

class Solution {        
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
            dfs(image, sr, sc, newColor, image[sr][sc]);
            return image;
        }

        private void dfs(int[][] image, int sr, int sc, int newColor, int startPixel) {
            if (sr >= image.length || sr < 0) return;
            if (sc >= image[sr].length || sc < 0) return;

            //시작 픽셀 비교
            if (image[sr][sc] != startPixel) return;
            
            if (image[sr][sc] == newColor) return;

            //픽셀 변경
            image[sr][sc] = newColor;

            dfs(image, sr + 1, sc, newColor, startPixel);
            dfs(image, sr - 1, sc, newColor, startPixel);
            dfs(image, sr, sc + 1, newColor, startPixel);
            dfs(image, sr, sc - 1, newColor, startPixel);
        }
}