class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
//如果新值和旧值一样,就没必要涂了
if(newColor == image[sr][sc]){
return image;
}
dfs(image,sr,sc,newColor,image[sr][sc]);
return image;
}
public void dfs(int[][] image, int sr, int sc, int newColor, int oldColor){
if(sr < 0 || sr >= image.length || sc < 0||sc >= image[sr].length || image[sr][sc]!=oldColor)
return;
image[sr][sc] = newColor;
dfs(image,sr-1,sc,newColor,oldColor);
dfs(image,sr+1,sc,newColor,oldColor);
dfs(image,sr,sc-1,newColor,oldColor);
dfs(image,sr,sc+1,newColor,oldColor);
}
}‘
解法一:深度优先搜索
解法二:广度优先搜索
此方法是深度优先搜索(递归)