题目
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:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
Solution
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
#define TTOMAP(i, j) ((i)*m+(j))
int n = grid.size();
if (n == 0) return 0;
int m = grid[0].size();
int count = 0;
vector<bool> visited(n*m, false);
for (int i = 0; i < n*m; i++) {
if (!visited[i] && grid[OTTF(i)][OTTS(i)] == '1') {
queue<int> q;
q.push(i);
visited[i] = true;
while (!q.empty()) {
int f = q.front();
int r = f / m, c = f % m;
if (r < n - 1 && grid[r+1][c] == '1' && !visited[TTOMAP(r+1, c)]) {
q.push(TTOMAP(r+1, c));
visited[TTOMAP(r+1, c)] = true;
}
if (c < m - 1 && grid[r][c+1] == '1' && !visited[TTOMAP(r, c+1)]) {
q.push(TTOMAP(r, c+1));
visited[TTOMAP(r, c+1)] = true;
}
if (r > 0 && grid[r-1][c] == '1' && !visited[TTOMAP(r-1, c)]) {
q.push(TTOMAP(r-1, c));
visited[TTOMAP(r-1, c)] = true;
}
if (c > 0 && grid[r][c-1] == '1' && !visited[TTOMAP(r, c-1)]) {
q.push(TTOMAP(r, c-1));
visited[TTOMAP(r, c-1)] = true;
}
q.pop();
}
count++;
}
visited[i] = true;
}
return count;
}
};
题解
是一个图的遍历问题:
- 记录每个节点的
visited
值为false
; - 从每个
visited = false
的节点出发,进行广度优先搜索(BFS); - 每次BFS遍历到的所有节点作为一个岛屿;
分析
使用BFS,虽然不是单根的,但是总体的复杂度还是O(n),即对每个节点进行最多一次访问(访问后立即设为visited = true
,因此不可能有第二次访问)