题目描述:

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:

1
2
3
4
11110
11010
11000
00000

Answer: 1

Example 2:

1
2
3
4
11000
11000
00100
00011

Answer: 3

使用BFS遍历即可.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
vector<vector<int>> visited;
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty()) return 0;
if(grid[0].empty()) return 0;
int islandNum = 0;
visited = vector<vector<int>>(grid.size(), vector<int>(grid[0].size(), false));
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == '1' && !visited[i][j]) {
BFS(grid, i, j);
++islandNum;
}
}
}
return islandNum;
}

void BFS(vector<vector<char>> &g, int x, int y){
visited[x][y] = true;
g[x][y] = '0';
queue<pair<int, int>> BFS;
BFS.push(pair<int, int>(x, y));
while(!BFS.empty()){
pair<int, int> pos = BFS.front();
int curX = pos.first, curY = pos.second;
if(curX - 1 >= 0 && g[curX - 1][curY] == '1' && !visited[curX - 1][curY]){
BFS.push(pair<int, int>(curX - 1, curY));
visited[curX - 1][curY] = true;
}
if(curX + 1 < g.size() && g[curX + 1][curY] == '1' && !visited[curX + 1][curY]){
BFS.push(pair<int, int>(curX + 1, curY));
visited[curX + 1][curY] = true;
}
if(curY - 1 >= 0 && g[curX][curY - 1] == '1' && !visited[curX][curY - 1]){
BFS.push(pair<int, int>(curX, curY - 1));
visited[curX][curY - 1] = true;
}
if(curY + 1 < g[0].size() && g[curX][curY + 1] == '1' && !visited[curX][curY + 1]){
BFS.push(pair<int, int>(curX, curY + 1));
visited[curX][curY + 1] = true;
}

BFS.pop();
}
}
};