前言
常规广搜和深搜.
时间复杂度:
m是图像矩阵列数,n是行数
- 广搜: O ( m × n ) O(m \times n) O(m×n)
- 深搜:
O
(
m
×
n
)
O(m \times n)
O(m×n)
空间复杂度: - 广搜: O ( m × n ) O(m \times n) O(m×n),主要在队列花销
- 深搜: O ( m × n ) O(m \times n) O(m×n),主要在栈花销
题目
源码
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 cur=image[sr][sc];
// if(cur==newColor){
// return image;
// }
// Queue<int[]>queue=new LinkedList<>();
// int n=image.length,m=image[0].length;
// image[sr][sc]=newColor;
// queue.offer(new int[]{sr,sc});
// while(!queue.isEmpty()){
// int [] box=queue.poll();
// int x=box[0],y=box[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]==cur){
// queue.offer(new int[]{mx,my});
// image[mx][my]=newColor;
// }
// }
// }
// return image;
// =======方法一,广度优先=========
// =======方法二,深度优先=========
int cur=image[sr][sc];
if(cur!=newColor){
dfs(image,sr,sc,cur,newColor);
}
return image;
// =======方法二,深度优先=========
}
// =======方法二,深度优先=========
public void dfs(int[][]image,int sr,int sc,int curColor,int newColor){
if(image[sr][sc]==curColor){
image[sr][sc]=newColor;
for(int i=0;i<4;i++){
int mx=sr+dx[i],my=sc+dy[i];
if(mx>=0 && mx<image.length && my >=0 && my<image[0].length){
dfs(image,mx,my,curColor,newColor);
}
}
}
}
// =======方法二,深度优先=========
}