class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int[][] vis = new int[image.length][image[0].length];
if(newColor == image[sr][sc]){
return image;
}
DFS(image, sr, sc, vis, newColor);
return image;
}
public static void DFS(int[][] image, int sr, int sc, int[][] vis, int newColor) {
int xMax = image.length;
int yMax = image[0].length;
int d = image[sr][sc];
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
stack1.add(sr);
stack2.add(sc);
vis[sr][sc] = 1;
image[sr][sc] = newColor;
while (!stack1.isEmpty() && !stack2.isEmpty()) {
int x = stack1.pop();
int y = stack2.pop();
if (x - 1 >= 0 && image[x - 1][y] == d && vis[x - 1][y] == 0) {
stack1.add(x - 1);
stack2.add(y);
vis[x - 1][y] = 1;
image[x-1][y] = newColor;
}
if (x + 1 < xMax && image[x + 1][y] == d && vis[x + 1][y] == 0) {
stack1.add(x + 1);
stack2.add(y);
vis[x + 1][y] = 1;
image[x+1][y] = newColor;
}
if (y - 1 >= 0 && image[x][y - 1] == d && vis[x][y - 1] == 0) {
stack1.add(x);
stack2.add(y - 1);
vis[x][y - 1] = 1;
image[x][y-1] = newColor;
}
if (y + 1 < yMax && image[x][y + 1] == d && vis[x][y + 1] == 0) {
stack1.add(x);
stack2.add(y + 1);
vis[x][y + 1] = 1;
image[x][y+1] = newColor;
}
}
}
}