1. 题目
2. 思路
(1) DFS
- 利用递归实现,注意要先改变当前下标的颜色再递归,否则会陷入死循环。
(2) BFS
3. 代码
import java.util.LinkedList;
import java.util.Queue;
public class Test {
public static void main(String[] args) {
Solution1 solution = new Solution1();
int[][] ints = solution.floodFill(new int[][]{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}, 1, 1, 2);
for (int[] anInt : ints) {
for (int i : anInt) {
System.out.println(i);
}
System.out.println();
}
}
}
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (newColor == image[sr][sc]) {
return image;
}
int oldColor = image[sr][sc];
image[sr][sc] = newColor;
if (sr > 0 && image[sr - 1][sc] == oldColor) {
floodFill(image, sr - 1, sc, newColor);
}
if (sr < image.length - 1 && image[sr + 1][sc] == oldColor) {
floodFill(image, sr + 1, sc, newColor);
}
if (sc > 0 && image[sr][sc - 1] == oldColor) {
floodFill(image, sr, sc - 1, newColor);
}
if (sc < image[0].length - 1 && image[sr][sc + 1] == oldColor) {
floodFill(image, sr, sc + 1, newColor);
}
return image;
}
}
class Solution1 {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
if (newColor == image[sr][sc]) {
return image;
}
int oldColor = image[sr][sc];
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{sr, sc});
image[sr][sc] = newColor;
while (!queue.isEmpty()) {
int[] index = queue.poll();
if (index[0] > 0 && image[index[0] - 1][index[1]] == oldColor) {
queue.offer(new int[]{index[0] - 1, index[1]});
image[index[0] - 1][index[1]] = newColor;
}
if (index[0] < image.length - 1 && image[index[0] + 1][index[1]] == oldColor) {
queue.offer(new int[]{index[0] + 1, index[1]});
image[index[0] + 1][index[1]] = newColor;
}
if (index[1] > 0 && image[index[0]][index[1] - 1] == oldColor) {
queue.offer(new int[]{index[0], index[1] - 1});
image[index[0]][index[1] - 1] = newColor;
}
if (index[1] < image[0].length - 1 && image[index[0]][index[1] + 1] == oldColor) {
queue.offer(new int[]{index[0], index[1] + 1});
image[index[0]][index[1] + 1] = newColor;
}
}
return image;
}
}