标签:
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
Answer: 3
简单的dfs
class Solution{ public: bool vis[1000][1000]; int m,n; void dfs(vector<vector<char>>&grid, int x, int y){ if(x < 0 || y < 0 || x >= m || y >= n || vis[x][y]) return; vis[x][y] = 1; if(grid[x][y] == '1'){ dfs(grid,x+1,y); dfs(grid,x-1,y); dfs(grid,x,y+1); dfs(grid,x,y-1); } } int numIslands(vector<vector<char>> &grid){ int cnt = 0; if(grid.size() == 0) return cnt; m = grid.size(); n = grid[0].size(); memset(vis,0,sizeof(vis)); for(int i = 0; i < grid.size(); i++) for(int j = 0; j < grid[0].size(); j++) if(!vis[i][j] && grid[i][j] == '1'){ dfs(grid,i,j); cnt++; } return cnt; } };
标签:
原文地址:http://blog.csdn.net/sina012345/article/details/45028599