677 - 大岛的数量

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;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值