广度搜索
先上代码
class Solution {
int[] dx = {1, 0, 0, -1};
int[] dy = {0, 1, -1, 0};//后面广搜用来遍历这俩然后遍历上下左右用的
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int currColor = image[sr][sc];//
if (currColor == newColor) {
return image;
}//如果已经是了就原样返回
int n = image.length, m = image[0].length;//长度和行长度
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(new int[]{sr, sc});//插入
image[sr][sc] = newColor;
//用队列
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int x = cell[0], y = cell[1];
for (int i = 0; i < 4; i++) {
int mx = x + dx[i], my = y + dy[i];
if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {
queue.offer(new int[]{mx, my});
image[mx][my] = newColor;//涂色
}
}
}
return image;
}
}
深度搜索
基于递归dfs方法实现
class Solution {
int[] dx = {1, 0, 0, -1};
int[] dy = {0, 1, -1, 0};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int currColor = image[sr][sc];
if (currColor != newColor) {
dfs(image, sr, sc, currColor, newColor);
}
return image;
}
public void dfs(int[][] image, int x, int y, int color, int newColor) {
if (image[x][y] == color) {
image[x][y] = newColor;
for (int i = 0; i < 4; i++) {
int mx = x + dx[i], my = y + dy[i];
if (mx >= 0 && mx < image.length && my >= 0 && my < image[0].length) {
dfs(image, mx, my, color, newColor);
}
}
}
}
}