【LeetCode】Number of Islands

133 篇文章 0 订阅
121 篇文章 2 订阅

Number of Islands 

Total Accepted: 8945 Total Submissions: 41107 My Submissions Question Solution 

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

11110
11010
11000
00000
Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

Credits:

Special thanks to @mithmatt for adding this problem and creating all test cases.

【解题思路】
1、题目大意为,1代表岛屿,2代表水。如果岛屿水平或者垂直相连,算一个岛。求所给的二次矩阵中岛屿的个数。
2、典型BFS,遍历每一个点,判断其相邻的点是否为1,如果为1即认为是同一个岛。
3、遍历结束,count的个数即为岛屿的个数。
Java AC
public class Solution {
    private int stepArr[][] = {{0,1},{0,-1},{1,0},{-1,0}};
    private int visit[][];
    private int m, n;
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0){
            return 0;
        }
        int count = 0;
        m = grid.length;
        n = grid[0].length;
        visit = new int[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == '1' && visit[i][j] == 0){
                    bfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    
    private void bfs(char grid[][], int i, int j){
        Queue<Integer> queue = new LinkedList<Integer>(); 
        queue.add(i * n + j);
        while(!queue.isEmpty()){
            int num = queue.poll();
            int x = num / n;
            int y = num % n;
                        
            for(int k = 0; k < 4; k++){
                int newX = x + stepArr[k][0];
                int newY = y + stepArr[k][1];
                if(newX >= 0 && newX < m && newY >= 0 && newY < n
                        && grid[newX][newY] == '1' && visit[newX][newY] == 0 ){
                        queue.add(newX * n + newY);
                        visit[newX][newY] = 1;
                }
            }
        }
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值