算法练习4-岛屿数量

给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。

岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。

此外,你可以假设该网格的四条边均被水包围。

来源:力扣 No.200

思路:

1、遍历二维网格,计算遇到‘1’的次数,即为最终结果;

2、当遇到二维网格的值为‘1’时,进行广度优先搜索BFS,将遇到的'1'变为'0';

3、继续遍历二维网格,遇到‘0’时continue。

坑:

二维网络里的值不是int类型而是char类型的字符

优化空间:

BFS循环中,往里面添加坐标时,会有重复判断的情况

代码:

class Solution {

    private static int m;
    private static int n;

    public int numIslands(char[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int res = 0;
        for(int x = 0; x < m; x++){
            for(int y = 0; y < n; y++){
                if(grid[x][y] == '0'){
                    continue;
                }
                res++;
                bfs(grid, x, y);
            }
        }

        return res;
    }

    public void bfs(char[][] grid, int cur_x, int cur_y){
        Stack<int[]> pos = new Stack<>();
        pos.push(new int[]{cur_x, cur_y});

        while(!pos.isEmpty()){
            int[] curPos = pos.pop();
            int curPos_x = curPos[0];
            int curPos_y = curPos[1];
            if(curPos_x >= m || curPos_y >= n || grid[curPos_x][curPos_y] == '0'){
                continue;
            }
            // System.out.println(curPos_x+" "+curPos_y+" "+grid[curPos_x][curPos_y] + " " +pos.size());
            grid[curPos_x][curPos_y] = '0';
            pos.push(new int[]{curPos_x+1, curPos_y});
            pos.push(new int[]{curPos_x, curPos_y+1});
            if(curPos_y - 1 >= 0){
                pos.push(new int[]{curPos_x, curPos_y-1});
            }if(curPos_x - 1 >= 0){
                pos.push(new int[]{curPos_x-1, curPos_y});
            }
        }
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值