今天看到Leetcode又有新题,故着手去做。题目比较简单,就是dfs或bfs的应用。
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.
题意:给定一个2维的网格地图,地图上为字符“1”或“0”,其中“1”为陆地,“0”为水域,默认地图周围都是由水构成。相连的陆地算作一个岛屿,求出地图中的岛屿总数。比如:
11110
11010
11000
00000
为1个岛屿。
11000
11000
00100
00011
为3个岛屿。
分析:只需要对每一个陆地区域做一次dfs,每次dfs中将已经遍历的陆地网格“1”变为水域网格“0”(防止再次遍历导致重复)。对每次dfs计数,总共dfs的次数即为岛屿总数。应注意,grid为空的特殊情况应该排除。
AC代码:
class Solution {
public:
int numIslands(vector<vector<char>> &grid) {
int row = grid.size();
if (!row) return 0;
int col = grid[0].size();
int count = 0;
for (unsigned i = 0; i != row; ++i) {
for (unsigned j = 0; j != col; ++j) {
if (grid[i][j] == '1') {
dfs(grid, i, j); ++count;
}
}
}
return count;
}
void dfs(vector<vector<char>> &grid, unsigned i, unsigned j) {
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int row = grid.size(), col = grid[0].size();
grid[i][j] = '0';
for (int k = 0; k != 4; ++k) {
int new_i = i + dx[k], new_j = j + dy[k];
if (new_i >=0 && new_i < row && new_j >= 0 && new_j < col && grid[new_i][new_j] == '1')
dfs(grid, new_i, new_j);
}
}
};如代码或分析有误,请批评指正,谢谢!
本文介绍了一道LeetCode上的经典题目——岛屿数量问题,并提供了一种基于深度优先搜索(DFS)的解决方案。通过遍历二维网格地图,利用递归方式标记相连的陆地为水域,从而统计岛屿数量。
1万+

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



