LeetCode 算法入门 Day7 广度优先搜索 / 深度优先搜索 Java
题目描述:
代码:
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 currColor = image[sr][sc];
if(currColor==newColor){
return image;
}
int n=image.length,m=image[0].length;
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(new int[] {sr,sc});
image[sr][sc]=newColor;
while(!queue.isEmpty()){
int []cell=queue.poll();
int x=cell[0],y=cell[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]==currColor){
queue.offer(new int[]{mx,my});
image[mx][my]=newColor;
}
}
}
return image;
}
}
思路:
问题描述:
代码:
class Solution {
public int maxAreaOfIsland(int[][] grid) {
int ans = 0;
for(int i=0;i!=grid.length;++i){
for(int j=0;j!=grid[0].length;++j){
int cur=0;
Queue<Integer> queuei = new LinkedList<Integer>();
Queue<Integer> queuej = new LinkedList<Integer>();
queuei.offer(i);
queuej.offer(j);
while(!queuei.isEmpty()){
int cur_i = queuei.poll(),cur_j=queuej.poll();
if(cur_i<0||cur_j<0||cur_i==grid.length||cur_j==grid[0].length||grid[cur_i][cur_j]!=1){
continue;
}
++cur;
grid[cur_i][cur_j]=0;
int[] di = {1,0,0,-1};
int[] dj = {0,1,-1,0};
for(int index=0;index!=4;index++){
int index_x=cur_i+di[index],index_y=cur_j+dj[index];
queuei.offer(index_x);
queuej.offer(index_y);
}
}
ans=Math.max(ans,cur);
}
}
return ans;
}
}
思路: