问题:
难度:easy
说明:
染色问题,将初始坐标sr,sc的颜色染成newColor,然后继续吧坐标上下左右四个地方和初始坐标一样颜色的格子一样染成newColor,再继续把染了色的格子上下左右四个和初始坐标一样颜色格子继续染色,如此类推,就是一个dfs(深扫)
输入案例:
// 在(sr,sc)就是(1,1)的地方,初始颜色为1,然后把1染成newColor 2,然后再把1上下左右四个等于1的都染色,再把染色的上下左右等于1继续染色,如此类推
image = [[1,1,1],
[1,1,0],
[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],
[2,2,0],
[2,0,1]]
我的代码:
马上用dfs,然后拿个队列处理,写的很随意,尽快做完
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
// 访问标记
int[][] visited = new int[image.length][image[0].length];
// 直接来个放得下所有元素的队列
int[][] queue = new int[image.length * image[0].length][2];
// 队列头
int begin = 0;
// 队列末
int end = 0;
// 放入初始
queue[begin] = new int[]{sr,sc};
int re = image[sr][sc];
visited[sr][sc] = 1;
// 使用循环
while(begin <= end) {
int[] site = queue[begin ++];
int y = site[0];
int x = site[1];
// 如果是一样颜色就染色
if(image[y][x] == re) image[y][x] = newColor;
// 上下左右四个地方
if(y + 1 < image.length && visited[y + 1][x] != 1 && image[y + 1][x] == re) {
queue[++ end] = new int[]{y + 1, x};
visited[y + 1][x] = 1;
}
if(y - 1 >= 0 && visited[y - 1][x] != 1 && image[y - 1][x] == re) {
queue[++ end] = new int[]{y - 1, x};
visited[y - 1][x] = 1;
}
if(x + 1 < image[0].length && visited[y][x + 1] != 1 && image[y][x + 1] == re) {
queue[++ end] = new int[]{y, x + 1};
visited[y][x + 1] = 1;
}
if(x - 1 >= 0 && visited[y][x - 1] != 1 && image[y][x - 1] == re) {
queue[++ end] = new int[]{y, x - 1};
visited[y][x - 1] = 1;
}
}
return image;
}
}