LeetCode 200. Number of islands (BFS)

Topic links: https://leetcode-cn.com/problems/number-of-islands/

Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

Example 1:

Enter:
11110
11010
11000
00000

Output: 1
Example 2:

Enter:
11000
11000
00100
00011

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

 

Guess you like

Origin www.cnblogs.com/shixinzei/p/12483788.html