Saturday, March 12, 2022

Leet Code 733. Flood Fill

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

I/P: 
[[1,1,1],[1,1,0],[1,0,1]]
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}}
1
1
1
O/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

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...