树和图(leetcode) : 岛屿数量
作者:互联网
给定一个由 '1'
(陆地)和 '0'
(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入: 11110 11010 11000 00000 输出: 1
示例 2:
输入: 11000 11000 00100 00011 输出: 3
解答(C++):
class Solution { public: //广度优先搜索 void dfs(vector<vector<char>>& grid, int x, int y) { int nx = grid.size(); int ny = grid[0].size(); grid[x][y] = '0'; if (x-1>=0 && grid[x-1][y] == '1') dfs(grid, x-1, y); if (x+1<nx && grid[x+1][y] == '1') dfs(grid, x+1, y); if (y-1>=0 && grid[x][y-1] == '1') dfs(grid, x, y-1); if (y+1<ny && grid[x][y+1] == '1') dfs(grid, x, y+1); } int numIslands(vector<vector<char>>& grid) { int island = 0; for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { if (grid[i][j] == '1') { ++island; dfs(grid, i, j); } } } return island; } };
标签:树和图,11000,int,岛屿,dfs,++,grid,leetcode,size 来源: https://www.cnblogs.com/vczf/p/12550172.html