릿코드(LEETCODE)

733. Flood Fill

cepiloth 2020. 3. 3. 11:32
반응형

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

 

sr, sc row, col 의 크기가 다를 수 있음을 주의

 

const int dx[] = { -1, 0, 0, 1 };
const int dy[] = { 0, -1, 1, 0 };
class Solution {
public:

    void dfs(vector<vector<int>>& image, int sr, int sc, int newColor, int dstColor) {
        image[sr][sc] = newColor;
        for (int i = 0; i < 4; i++) {
            int cy = sr + dy[i];
            int cx = sc + dx[i];

            if (cx < 0 || cx >= image[0].size()) {
                continue;
            }

            if (cy < 0 || cy >= image.size()) {
                continue;
            }

            if (image[cy][cx] == dstColor) {
                dfs(image, cy, cx, newColor, dstColor);
            }
        }
    }
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {

        int dstColor = image[sr][sc];
        if (image[sr][sc] == newColor) return image;
        dfs(image, sr, sc, newColor, dstColor);
        return image;
    }
};
반응형