DFS或BFS(深度优先搜索或广度优先搜索遍历无向图)-04-无向图-岛屿数量
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
1 class Solution { 2 public: 3 int dist[4][2] = {0,1,0,-1,1,0,-1,0}; 4 queue<pair<int,int>>que; 5 void dfs(vector<vector<char>>& grid,vector<vector<int>>& sign,int i,int j,int row,int col,int num){ 6 sign[i][j] = 1; 7 int ii,jj; 8 for(int zz = 0;zz < 4;zz++){ 9 ii = i + dist[zz][0]; 10 jj = j + dist[zz][1]; 11 if(ii < 0||jj < 0||ii >= row||jj >= col) continue; 12 if(sign[ii][jj] == 1) continue; 13 if(grid[ii][jj] == '1') 14 dfs(grid,sign,ii,jj,row,col,num); 15 } 16 } 17 void bfs(vector<vector<char>>& grid,vector<vector<int>>& sign,int i,int j,int row,int col,int num){ 18 sign[i][j] = 1; 19 int ii,jj; 20 for(int zz = 0;zz < 4;zz++){ 21 ii = i + dist[zz][0]; 22 jj = j + dist[zz][1]; 23 if(ii < 0||jj < 0||ii >= row||jj >= col) continue; 24 if(sign[ii][jj] == 1) continue; 25 if(grid[ii][jj] == '1'){ 26 sign[ii][jj] = 1; 27 que.push({ii,jj}); 28 } 29 } 30 while(!que.empty()){ 31 ii = que.front().first; 32 jj = que.front().second; 33 que.pop(); 34 bfs(grid,sign,ii,jj,row,col,num); 35 } 36 37 } 38 int numIslands(vector<vector<char>>& grid) { 39 if(grid.size() == 0||grid[0].size() == 0) 40 return 0; 41 int row = grid.size(); 42 int col = grid[0].size(); 43 int num = 0; 44 vector<vector<int>>sign(row,vector<int>(col,0)); 45 for(int i = 0 ;i < row;i++){ 46 for(int j = 0;j < col;j++){ 47 if(sign[i][j] == 0 && grid[i][j] == '1'){ 48 num++; 49 dfs(grid,sign,i,j,row,col,num); 50 } 51 } 52 } 53 return num; 54 } 55 };
可以的话,记得帮我点个推荐,然后收藏+关注哟