题目:
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
思路:
一道典型的DFS的题目。这道题目本身没有什么特别之处,但是这里的代码比较具有DFS的典型特征,可以作为一种面试类似题目的模板。
代码:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.size() == 0 || grid[0].size() == 0) {
return 0;
}
int row_num = grid.size(), col_num = grid[0].size();
int res = 0;
for(int row = 0; row < row_num; ++row) {
for(int col = 0; col < col_num; ++col) {
if(grid[row][col] == '1') {
++res;
dfs(grid, row, col, row_num, col_num);
}
}
}
return res;
}
private:
void dfs(vector<vector<char>>& grid, int row, int col, int row_num, int col_num) {
if(row >= 0 && row < row_num && col >= 0 && col < col_num && grid[row][col] == '1') {
grid[row][col] = '2';
dfs(grid, row + 1, col, row_num, col_num);
dfs(grid, row - 1, col, row_num, col_num);
dfs(grid, row, col + 1, row_num, col_num);
dfs(grid, row, col - 1, row_num, col_num);
}
}
};
本文介绍了一种使用深度优先搜索(DFS)算法解决岛屿计数问题的方法。通过遍历二维网格,利用DFS标记并计数岛屿数量,适用于所有边框被水包围的情况。
401

被折叠的 条评论
为什么被折叠?



