- Number of Islands
Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
Find the number of islands.
Example
Example 1:
Input:
[
[1,1,0,0,0],
[0,1,0,0,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,0,0,1]
]
Output:
3
Example 2:
Input:
[
[1,1]
]
Output:
1
这题是经典宽搜(BFS)题。有3种解法,BFS,并查集和DFS。
解法1: BFS
注意:
1)遍历每个节点,若为1,则调用bfs。
2)bfs的主要作用就是从该节点向4个方向扩展,把相连的节点设为false。这里要注意的是,把相连的节点设为false后,该节点还是要进queue,不然该方向的宽搜就断了。
3)可以用两个数组dirX和dirY和一个for循环(0…3)来搜索4个方向。
4)每次调用bfs的时候,该节点本身要设为false,这样就不会重复查找了。
5) 每次调用bfs的时候,num_islands只加1,因为所有相连的节点加起来只能算一个。
6) queue里面放coordinate的值而不是指针。
7) queue的操作是
queue.pop() //不返回值
queue.push(node) //从back push
queue.front() //返回queue最front的元素
注意网上有的地方用queue.pop_front()和queue.push_back()。这两个函数我试了不支持,可能是C++版本不一样的原因?
代码如下:
struct coordinate {
int x;
int y;
coordinate (int x, int y) {
this->x=x;
this->y=y;
}
};
int numIslands(vector<vector<bool>> &grid) {
int num_row=grid.size();
if (num_row==0) return 0;
int num_col=grid[0].size();
int num_islands=0;
for (int i=0; i<num_row; ++i) {
for (int j=0; j<num_col; ++j) {
if (grid[i][j]) {
bfs(grid, i, j);
num_islands++;
}
}
}
return num_islands;
}
void bfs(vector<vector<bool>> &grid, int x, int y) {
//north, east, west, south
vector<int> dirX = {0,1,-1,0};
vector<int> dirY = {1,0,0,-1};
queue<coordinate> q;
q.push(coordinate(x,y)); //also we can use coordinate temp = coordinate(x, y); and q.push(temp);
grid[x][y]=false;
while(!q.empty()) {
coordinate node = q.front();
q.pop();
for (int i=0; i<4; i++) {
coordinate neighbour = coordinate(node.x+dirX[i], node.y+dirY[i]);
if (!(neighbour.x>=0 && neighbour.x<grid.size() && neighbour.y>=0 && neighbour.y<grid[0].size()))
continue;
if (grid[neighbour.x][neighbour.y]) {
grid[neighbour.x][neighbour.y]=false;
q.push(neighbour);
}
}
}
}
二刷:
class Solution {
public:
/**
* @param grid: a boolean 2D matrix
* @return: an integer
*/
int numIslands(vector<vector<bool>> &grid) {
int rowSize = grid.size();
if (rowSize == 0) return 0;
int colSize = grid[0].size();
if (colSize == 0) return 0;
int res = 0;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
queue<pair<int, int>> q;
vector<vector<bool>> visited(rowSize, vector<bool>(colSize, false));
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (!visited[i][j] && grid[i][j] == 1) {
res++;
q.push({i, j});
} else {
continue;
}
while (!q.empty()) {
auto frontNode = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int newX = frontNode.first + dx[k];
int newY = frontNode.second + dy[k];
if (newX < 0 || newX >= rowSize ||
newY < 0 || newY >= colSize ||
visited[newX][newY] ||
grid[newX][newY] == 0
) continue;
q.push({newX, newY});
visited[newX][newY] = true;
}
}
}
}
return res;
}
};
解法2:并查集 union-find。记得二维矩阵可以用i*col+j来转换成一维。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int n_row = grid.size();
int n_col = grid[0].size();
father.resize(n_row * n_col + 1);
//initialize, each node's father is itself
for (int i = 0; i < n_row; i++) {
for (int j = 0; j < n_col; j++) {
int num = i * n_col + j;
father[num] = num;
if (grid[i][j] == '1') ans++;
}
}
// vector<int> dx = {1, 0};
// vector<int> dy = {0, 1};
vector<int> dx = {0, 0, 1, -1};
vector<int> dy = {1, -1, 0, 0};
for (int i = 0; i < n_row; i++) {
for (int j = 0; j < n_col; j++) {
if (grid[i][j] == '1') {
for (int k = 0; k < 4; k++) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 && newX < n_row &&
newY >= 0 && newY < n_col &&
grid[newX][newY] == '1') {
join(i * n_col + j, newX * n_col + newY);
}
}
}
}
}
return ans;
}
private:
vector<int> father;
int ans = 0;
int find(int x) {
if (father[x] == x) {
return x;
}
return father[x] = find(father[x]);
}
void join(int x, int y) {
int fatherX = find(x);
int fatherY = find(y);
if (fatherX != fatherY) {
father[fatherX] = fatherY;
ans--;
}
}
};
改进:其实并查集的话,用右和下2个方向就可以了,因为执行到后面的时候,前面的都必然已经处理过了。
注意: DFS和BFS不能这么用! 看下面的例子
111
010
111
当DFS/BFS执行到num[2,1] 这个1(行列序号都从0开始)的时候,它是没有办法往左扩展的,所以num[2,0]这个1没法跟它连在一起。所以num[2,0]又会重新来一次BFS/DFS,而重新来一次的话,count就会加1,这样,就多算了一次。上图会被判为2个岛。
而并查集为什么可以呢?因为并查集算法是先把count初始化为所有的1的个数,然后,每次join的时候count–。这样,虽然num[2.1]不会主动连到num[2,0],但是轮到num[2,0]的时候,它会主动join num[2,1],这样count又会减1。答案正确。
int numIslands(vector<vector<char>>& grid) {
int n_row = grid.size();
int n_col = grid[0].size();
father.resize(n_row * n_col + 1);
//initialize, each node's father is itself
for (int i = 0; i < n_row; i++) {
for (int j = 0; j < n_col; j++) {
int num = i * n_col + j;
father[num] = num;
if (grid[i][j] == '1') ans++;
}
}
vector<int> dx = {1, 0};
vector<int> dy = {0, 1};
for (int i = 0; i < n_row; i++) {
for (int j = 0; j < n_col; j++) {
if (grid[i][j] == '1') {
for (int k = 0; k < 2; k++) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 && newX < n_row &&
newY >= 0 && newY < n_col &&
grid[newX][newY] == '1') {
join(i * n_col + j, newX * n_col + newY);
}
}
}
}
}
return ans;
}
解法3:深搜DFS。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int n_row = grid.size();
int n_col = grid[0].size();
int count = 0;
for (int i = 0; i < n_row; i++) {
for (int j = 0; j < n_col; j++) {
if (grid[i][j] == '1') {
dfs(grid, i, j);
count++;
}
}
}
return count;
}
private:
void dfs(vector<vector<char>> &grid, int i, int j) {
grid[i][j] = 0;
int n_row = grid.size();
int n_col = grid[0].size();
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
for (int k = 0; k < 4; ++k) {
int newX = i + dx[k];
int newY = j + dy[k];
if (newX >= 0 &&
newX < n_row &&
newY >= 0 &&
newY < n_col &&
grid[newX][newY] == '1') {
dfs(grid, newX, newY);
}
}
}
};
二刷:
class Solution {
public:
/**
* @param grid: a boolean 2D matrix
* @return: an integer
*/
int numIslands(vector<vector<bool>> &grid) {
int rowSize = grid.size();
if (rowSize == 0) return 0;
int colSize = grid[0].size();
if (colSize == 0) return 0;
int res = 0;
vector<vector<bool>> visited(rowSize, vector<bool>(colSize, false));
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++) {
if (!visited[i][j] && grid[i][j] == 1) {
res++;
dfs(grid, i, j, visited);
}
}
}
return res;
}
private:
void dfs(vector<vector<bool>>& grid, int row, int col, vector<vector<bool>>& visited) {
int rowSize = grid.size();
if (rowSize == 0) return;
int colSize = grid[0].size();
if (colSize == 0) return;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
for (int i = 0; i < 4; i++) {
int newX = row + dx[i];
int newY = col + dy[i];
if (newX < 0 || newX >= rowSize ||
newY < 0 || newY >= colSize ||
visited[newX][newY] ||
grid[newX][newY] == 0) {
continue;
}
visited[newX][newY] = true;
dfs(grid, newX, newY, visited);
}
}
};