问题描述:给你一个int矩阵,起始坐标,sr,sc。新的数值newColor。将起始坐标数值改成newColor。并将与起始坐标上下左右相连的各个坐标,如果其值与起始坐标值相等的坐标也改成newColor,并重复此过程。简而言之,所有矩阵中与起始位置的数值相同的点。如果可以通过上下左右移动的方式到达起始位置,将数值改成newColor。
思路:递归,再利用一个数组进行是否已更改此点的记录。避免两个相邻数字都是目标值结果无限递归。
原代码:
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int val=image[sr][sc];
int row=image.length;
int col=image[0].length;
int[][] record=new int[row][col];
return floodFill(image,record,sr,sc,newColor,val);
}
private int[][] floodFill(int[][] image,int[][] record, int sr, int sc, int newColor, int targetValue) {
int row=image.length;
int col=image[0].length;
if(sr>=0&&sr<row&&sc>=0&&sc<col){
if(image[sr][sc]==targetValue&&record[sr][sc]==0){
image[sr][sc]=newColor;
record[sr][sc]=1;
image=floodFill(image,record,sr+1,sc,newColor,targetValue);
image=floodFill(image,record,sr-1,sc,newColor,targetValue);
image=floodFill(image,record,sr,sc-1,newColor,targetValue);
image=floodFill(image,record,sr,sc+1,newColor,targetValue);
return image;
}else
return image;
}else
return image;
}
最佳答案:
private int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
boolean[][] visited = new boolean[image.length][image[0].length];
helper(image, sr, sc, newColor, image[sr][sc], visited);
return image;
}
private void helper(int[][] image, int sr, int sc, int newColor, int oldColor, boolean[][] visited) {
if (sr < 0 || sr >= image.length) {
return;
}
if (sc < 0 || sc >= image[0].length) {
return;
}
if (visited[sr][sc]) {
return;
}
if (image[sr][sc] != oldColor) {
return;
}
image[sr][sc] = newColor;
visited[sr][sc] = true;
for (int[] dir : dirs) {
helper(image, sr + dir[0], sc + dir[1], newColor, oldColor, visited);
}
}
最佳答案中:使用boolean数组进行记录该点是否已访问。并且,还有个亮点是通过循环预定义数组来达到遍历矩阵的目的。