2017.10.30
采用深度遍历的方法,找到相连的岛屿并计数,如果最后的计数量大于给定的k,那么res + 1;
public class Solution {
/*
* @param : a 2d boolean array
* @param : an integer
* @return: the number of Islands
*/
public static int numsofIsland(boolean[][] grid, int k) {
// Write your code here
int m = grid.length;
int n = grid[0].length;
int res = 0;
boolean[][] visit = new boolean[m][n];
LinkedList<int[]> stack = new LinkedList<>();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int count = 0;
if(grid[i][j] == true && visit[i][j] == false){
int[] tmp = new int[2];
tmp[0] = i;
tmp[1] = j;
visit[i][j] = true;
stack.push(tmp);
count++;
}
while(!stack.isEmpty()){
int[] tmp = stack.peek();
int[] next = findNext(grid,visit,tmp[0],tmp[1]);
if(next[0] != -1 && next[1] != -1){
visit[next[0]][next[1]] = true;
stack.push(next);
count++;
}
else{
stack.pop();
}
}
//System.out.println(count);
if(count >= k){
res ++;
}
}
}
return res;
}
public static int[] findNext(boolean[][] grid, boolean[][] visit,int x,int y){
int[] res = new int[2];
res[0] = -1;
res[1] = -1;
int m = grid.length;
int n = grid[0].length;
if(x != 0 && grid[x-1][y] == true && visit[x-1][y] == false){
res[0] = x-1;
res[1] = y;
return res;
}
if(x != m-1 && grid[x+1][y] == true && visit[x+1][y] == false){
res[0] = x+1;
res[1] = y;
return res;
}
if(y != 0 && grid[x][y-1] == true && visit[x][y-1] == false){
res[0] = x;
res[1] = y-1;
return res;
}
if(y != n-1 && grid[x][y+1] == true && visit[x][y+1] == false){
res[0] = x;
res[1] = y+1;
return res;
}
return res;
}
};