forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloodFill.java
More file actions
28 lines (23 loc) · 855 Bytes
/
FloodFill.java
File metadata and controls
28 lines (23 loc) · 855 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package graph;
/**
* Description: https://leetcode.com/problems/flood-fill
* Difficulty: Easy
* Time complexity: O(m * n)
* Space complexity: O(m * n)
*/
public class FloodFill {
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
recolor(image, sr, sc, image[sr][sc], color);
return image;
}
private void recolor(int[][] image, int x, int y, int oldColor, int newColor) {
if (x < 0 || x >= image.length) return;
if (y < 0 || y >= image[0].length) return;
if (image[x][y] != oldColor || image[x][y] == newColor) return;
image[x][y] = newColor;
recolor(image, x + 1, y, oldColor, newColor);
recolor(image, x - 1, y, oldColor, newColor);
recolor(image, x, y + 1, oldColor, newColor);
recolor(image, x, y - 1, oldColor, newColor);
}
}