LintCode 433 Number of Islands

54 篇文章 2 订阅
13 篇文章 0 订阅

思路

BFS, 从全图中所有为1的地方开始BFS,向4个方向进行搜索,在将起点加入queue的同时将其标记为0或者开一个visit数组标记已访问。

复杂度

  • 时间复杂度O(n*m)
  • 空间复杂度O(n*m)

代码

class Coordinate {
    int x, y;
    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Solution {
    /**
     * @param grid: a boolean 2D matrix
     * @return: an integer
     */
    public int numIslands(boolean[][] grid) {
        // write your code here
        if (grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == true) {
                    bfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    
    private void bfs(boolean[][] grid, int x, int y) {
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        Queue<Coordinate> queue = new LinkedList<>();
        queue.offer(new Coordinate(x, y));
        grid[x][y] = false;
        while (!queue.isEmpty()) {
            Coordinate coor = queue.poll();
            for (int i = 0; i < 4; i++) {
                Coordinate next = new Coordinate(
                    coor.x + dx[i],
                    coor.y + dy[i]
                );
                if (!inBound(next, grid)) {
                    continue;
                }
                if (grid[next.x][next.y]) {
                    queue.offer(next);
                    grid[next.x][next.y] = false;
                }
            }
        }
    }
    
    private boolean inBound(Coordinate coor, boolean[][] grid) {
        return 0 <= coor.x && coor.x < grid.length && 
                0 <= coor.y && coor.y < grid[0].length; 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值