LeetCode 200. Number of Islands (并查集)
Tags:
* Depth-first Search
* Breadth-first Search
* Union Find
问题描述
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
解题思路
问题意思是:
给一个用0和1组成的2维矩阵,0表示水,1表示陆地。被水包围的陆地就是岛。
1(陆地)相连组成岛,只能垂直或者水平相连,不能对角相连。
要求返回矩阵中岛的个数。
可以使用并查集,将相连的1都连成一个部分,最后得出部分总数就是岛的数量。
参考代码
/*
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
*/
#include <iostream>
#include <vector>
using namespace std;
class UF
{
public:
int *id;
int *sz;
int count;
public:
UF(int N)
{
id = new int[N];
sz = new int[N];
count = N;
for (int i = 0; i < N; ++i)
{
id[i] = i;
sz[i] = 1;
}
}
~UF()
{
delete[] id;
delete[] sz;
}
int find(int i)
{
while(id[i] != i)
{
id[i] = id[id[i]];
i = id[i];
}
return i;
}
bool connected(int p, int q)
{
return find(p) == find(q);
}
void connect(int p, int q)
{
int a = find(p);
int b = find(q);
if (a == b) return;
if(sz[a] < sz[b])
{
id[a] = b;
sz[b] += sz[a];
}
else
{
id[b] = a;
sz[a] += sz[b];
}
--count;
}
};
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int zeroCount = 0; // number of water grid
int row = grid.size();
if (row == 0)return 0;
int col = grid[0].size();
UF uf = UF(row * col);
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
cout << "row = " <<i << ", col = " << j << endl;
if(grid[i][j] == '1')
{
if (i - 1 >= 0 && grid[i - 1][j] == '1')
uf.connect(i * col + j, (i - 1) * col + j);
if (i + 1 < row && grid[i + 1][j] == '1')
uf.connect(i * col + j, (i + 1) * col + j);
if (j - 1 >= 0 && grid[i][j - 1] == '1')
uf.connect(i * col + j, i * col + j - 1);
if (j + 1 < col && grid[i][j + 1] == '1')
uf.connect(i * col + j, i * col + j + 1);
}
else
++zeroCount;
}
}
return uf.count - zeroCount;
}
};
int main()
{
vector<vector<char>> grid =
{
{ '1', '1', '0', '0', '0' },
{ '1', '1', '0', '0', '0' },
{ '0', '0', '1', '0', '0' },
{ '0', '0', '0', '1', '1' }
};
auto sl = new Solution();
cout << sl->numIslands(grid) << endl;
system("pause");
return 0;
}