200. 岛屿数量

 1 class Solution 
 2 {
 3 public:
 4     int numIslands(vector<vector<char>>& grid) 
 5     {
 6         if(grid.size() == 0 || grid[0].size() == 0) return 0;
 7         int m = grid.size();
 8         int n = grid[0].size();
 9         int count = 0;
10         for(int i = 0;i < m;i ++)
11         {
12             for(int j = 0;j < n;j ++)
13             {
14                 if(grid[i][j] == '1')
15                 {
16                     count++;
17                     DFS(grid,m,n,i,j);
18                 }
19             }
20         }
21         return count;
22     }
23 
24     void DFS(vector<vector<char>>& grid,int m,int n,int i,int j)
25     {
26         if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') return;
27         grid[i][j] = '0';
28         DFS(grid,m,n,i + 1,j);
29         DFS(grid,m,n,i - 1,j);
30         DFS(grid,m,n,i,j + 1);
31         DFS(grid,m,n,i,j - 1);
32     }
33 };

 

 1 class UnionFind 
 2 {
 3 public:
 4     vector<int> parent; // 存储若干棵树
 5     UnionFind(int n) 
 6     {
 7         for (int i = 0; i < n; i++)  parent.push_back(i);
 8     }
 9     /* 返回节点 x 的根节点 */
10     int Find(int x) 
11     {
12         // 进行路径压缩
13         if (parent[x] != x) parent[x] = Find(parent[x]);
14         return parent[x];
15     }
16     void Union(int p, int q) 
17     {
18         int rootP = Find(p);
19         int rootQ = Find(q);
20         if (rootP == rootQ) return;
21 
22         parent[rootQ] = rootP;
23     }
24 };
25 
26 class Solution 
27 {
28     int dx[4] = {-1,0,1,0};
29     int dy[4] = {0,1,0,-1};
30 public:
31     int numIslands(vector<vector<char>>& grid) 
32     {
33         if(grid.empty() || grid[0].empty()) return 0;
34         int m = grid.size(),n = grid[0].size();
35         UnionFind uf(m * n);
36         for(int i = 0;i < m;i ++)
37         {
38             for(int j = 0;j < n;j ++)
39             {
40                 if(grid[i][j] == '1')
41                 {
42                     for(int k = 0;k < 4;k ++)
43                     {
44                         int x = i + dx[k];
45                         int y = j + dy[k];
46                         if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1')
47                         {
48                             uf.Union(i*n+j,x*n+y);
49                         }
50                     }
51                 }
52             }
53         }
54         int res = 0;
55         for(int i = 0;i < m;i ++)
56         {
57             for(int j = 0;j < n;j ++)
58             {
59                 if(grid[i][j] == '1')
60                 {
61                     int id = i*n+j;
62                     //当前节点是不是带头大哥,如果是,res++。因为每一个连通图都有一个带头大哥
63                     if(uf.Find(id) == id) res ++;
64                 }
65             }
66         }
67         return res;
68     }
69 };

 

posted @ 2020-04-04 14:51  Jinxiaobo0509  阅读(119)  评论(0)    收藏  举报