链接
LeetCode题目:https://leetcode.com/problems/number-of-islands/
难度:Medium
题目
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.
‘1’是陆地,‘0’是海水,计算出小岛数量。
![]()
例子一有1座小岛。
![]()
例子二有3座小岛。
分析
这题可以用dfs算法,但我选择了更简单的并查集,它是一种树型的数据结构,其保持着用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。大致做法是先把陆地和四周的其中一块陆地合并,再通过并查集合并到根节点,最后统计树的数目即是小岛数目。
代码
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
int numIslands(vector<vector<char>> &grid) {
if (grid.size() == 0 || grid[0].size() == 0) return 0;
int height = (int) grid.size();
int width = (int) grid[0].size();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (grid[i][j] == '0') father.push_back(-1);
else father.push_back(i * width + j);
rank.push_back(0);
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (grid[i][j] == '0') continue;
for (int k = 0; k < 4; k++) {
int x = i + step[k][0];
int y = j + step[k][1];
if (x < 0 || x >= height || y < 0 || y >= width
|| grid[x][y] == '0')
continue;
make(i * width + j, x * width + y);
}
}
}
unordered_set<int> islands;
for (int i = 0; i < father.size(); i++) {
if (father[i] != -1) {
islands.insert(find(i));
}
}
return (int) islands.size();
}
int find(int x) {
if (father[x] != x) father[x] = find(father[x]);
return father[x];
}
void make(int x, int y) {
int p = find(x), q = find(y);
if (p == q) return;
if (rank[p] > rank[q]) father[q] = p;
else {
if (rank[p] == rank[q]) rank[q]++;
father[p] = q;
}
}
private:
vector<int> father, rank;
const int step[4][2] = {{-1, 0},
{1, 0},
{0, -1},
{0, 1}};
};