题目地址:
https://leetcode.com/problems/flood-fill/
给定一个矩阵,给定一个出发点和一个颜色值,要将其与出发点连通且与出发点颜色相同的点都染色成新的颜色。
法1:BFS。
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (image == null || image.length == 0 || image[0].length == 0) {
return image;
}
int color = image[sr][sc];
boolean[][] visited = new boolean[image.length][image[0].length];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{sr, sc});
int[][] d = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
while (!queue.isEmpty()) {
int[] cur = queue.poll();
image[cur[0]][cur[1]] = newColor;
visited[cur[0]][cur[1]] = true;
for (int i = 0; i < 4; i++) {
int newX = cur[0] + d[i][0];
int newY = cur[1] + d[i][1];
if (0 <= newX && newX < image.length && 0 <= newY && newY < image[0].length
&& image[newX][newY] == color && !visited[newX][newY]) {
queue.offer(new int[]{newX, newY});
}
}
}
return image;
}
}
法2:DFS。
public class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (image == null || image.length == 0 || image[0].length == 0) {
return image;
}
int oldColor = image[sr][sc];
boolean[][] visited = new boolean[image.length][image[0].length];
int[][] d = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
dfs(image, sr, sc, newColor, oldColor, visited, d);
return image;
}
private void dfs(int[][] image, int x, int y, int newColor, int oldColor, boolean[][] visited, int[][] d) {
image[x][y] = newColor;
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int newX = x + d[i][0];
int newY = y + d[i][1];
if (0 <= newX && newX < image.length && 0 <= newY && newY < image[0].length
&& image[newX][newY] == oldColor && !visited[newX][newY]) {
dfs(image, newX, newY, newColor, oldColor, visited, d);
}
}
}
}