733. 图像渲染
难度:简单
2020/8/16每日一题打卡√
题目描述
解题思路
题目真的又臭又长,但是读懂之后发现就是单纯的简单的图搜索问题,dfs或者bfs都能搞定
DFS
写dfs的时候总忘记加访问数组,结果就爆栈
/*
* 733. 图像渲染
* 2020/8/16
* 难度:简单
*/
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
boolean[][] visit = new boolean[image.length][image[0].length];
dfsFloodFill(image, sr, sc, newColor, image[sr][sc],visit);
return image;
}
public void dfsFloodFill(int[][] image, int sr, int sc, int newColor,int oldColor,boolean[][] visit) {
System.out.println(sr+" "+sc);
//如果数组越界或者不等于开始节点的颜色值
if(sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != oldColor || visit[sr][sc]) {
return;
}
image[sr][sc] = newColor;
visit[sr][sc] = true;
dfsFloodFill(image, sr+1, sc, newColor, oldColor,visit);
dfsFloodFill(image, sr-1, sc, newColor, oldColor,visit);
dfsFloodFill(image, sr, sc+1, newColor, oldColor,visit);
dfsFloodFill(image, sr, sc-1, newColor, oldColor,visit);
}
BFS
就是套模板
public int[][] floodFill1(int[][] image, int sr, int sc, int newColor) {
int[][] move = new int[][] {{1,0},{-1,0},{0,1},{0,-1}};
boolean[][] visit = new boolean[image.length][image[0].length];
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(sr, sc));
int oldColor = image[sr][sc];
while(!queue.isEmpty()) {
Point temp = queue.poll();
visit[temp.x][temp.y] = true;
image[temp.x][temp.y] = newColor;
for (int i = 0; i < move.length; i++) {
int x = temp.x + move[i][0];
int y = temp.y + move[i][1];
if(x < 0 || x >= image.length || y < 0 || y >= image[0].length || image[x][y] != oldColor || visit[x][y]) {
System.out.println(x+" "+y);
continue;
}else {
queue.add(new Point(x, y));
}
}
}
return image;
}