https://leetcode.com/problems/flood-fill/
I/P:
[[1,1,1],[1,1,0],[1,0,1]]
1
1
2
1
1
2
O/P: [[2,2,2],[2,2,0],[2,0,1]]
Edge Case: when old color and new color are same.
I/P:
{{0, 0, 0}, {0, 1, 1}}111O/P: {{0, 0, 0}, {0, 1, 1}}
package pep.Day43;
public class TxnFee {
public static void main(String[] args) {
System.out.println(floodFill(new int[][]{{0, 0, 0}, {0, 1, 1}}, 1, 1, 1));
}
public static int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int oldColor = image[sr][sc];
dfs(image, sr, sc, oldColor, newColor);
return image;
}
public static void dfs(int[][] image, int row, int col, int oldColor, int newColor) {
if ((oldColor == newColor) || (image[row][col] != oldColor && image[row][col] != newColor))
return;
if (image[row][col] == oldColor && oldColor != newColor)
image[row][col] = newColor;
int[][] dirns = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
for (int[] dir : dirns) {
int x = dir[0] + row;
int y = dir[1] + col;
if ((x >= 0 && x < image.length) && (y >= 0 && y < image[0].length)) {
if (image[x][y] == oldColor) {
dfs(image, x, y, oldColor, newColor);
}
}
}
}
}
No comments:
Post a Comment