首页 > 其他 > 详细

LeetCode 200. 岛屿数量 (BFS)

时间:2020-03-13 02:28:05      阅读:79      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode-cn.com/problems/number-of-islands/

给定一个由 ‘1‘(陆地)和 ‘0‘(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:
11110
11010
11000
00000

输出: 1
示例 2:

输入:
11000
11000
00100
00011

输出: 3

 1 class Solution {
 2 public:
 3     typedef pair<int,int> P;
 4     int N,M;
 5     int dx[4]={1,0,0,-1};
 6     int dy[4]={0,-1,1,0};
 7     int x,y,nx,ny;
 8     int numIslands(vector<vector<char>>& grid) {
 9         if(grid.size()==0) return 0;
10         int res=0;
11         N=grid.size(),M=grid[0].size();
12         for(int i=0;i<N;i++){
13             for(int j=0;j<M;j++){
14                 if(grid[i][j]==1){
15                     res++;
16                     int sx=i,sy=j;
17                     queue<P> que;
18                     que.push(P(sx,sy));
19                     while(!que.empty()){
20                         P p=que.front();
21                         que.pop();
22                         x=p.first,y=p.second;
23                         for(int i=0;i<4;i++){
24                             nx=x+dx[i],ny=y+dy[i];
25                             if(nx>=0&&nx<N&&ny>=0&&ny<M&&grid[nx][ny]==1){
26                                 grid[nx][ny]=0;
27                                 que.push(P(nx,ny));
28                             }
29                         }
30                     }
31                 }
32             }
33         }
34         return res;
35     }
36 };

 

LeetCode 200. 岛屿数量 (BFS)

原文:https://www.cnblogs.com/shixinzei/p/12483788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!