问题描述:
算法思想:
采用深度优先遍历(DFS),每次经过一个节点就把该节点置为非1,避免之后重复遍历。程序从一个值为1的点开始遍历,直到无法继续下去,则认为这座岛屿探索完了,继续寻找下一个值为1的节点,直到整个图都遍历完。
代码:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int islands = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
if (grid[i][j] == '1') {
findLand(grid, i, j);
islands++;
}
}
}
return islands;
}
void findLand(vector<vector<char>>& grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.size() || j >= grid[i].size() || grid[i][j] != '1') {
return;
}
grid[i][j] = '0';
findLand(grid, i, j + 1);
findLand(grid, i, j - 1);
findLand(grid, i + 1, j);
findLand(grid, i - 1, j);
}
};