Number of Islands BFS
2015-06-01 17:46
281 查看
Number of Islands
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
class Solution { public: int numIslands(vector<vector<char>>& grid) { if(grid.empty() || grid[0].empty()) return 0; int n=grid.size(); int m=grid[0].size(); int i,j,sum; sum=0; for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(grid[i][j]=='1') { sum++; bfs(i,j,grid,n,m); } } } return sum; } void bfs(int x,int y,vector<vector<char>> &grid,int n,int m) { queue<int> q; q.push(x*m+y); grid[x][y]='0'; while(!q.empty()) { int cur=q.front(); q.pop(); int xx=cur/m; int yy=cur%m; if(xx+1<n&&grid[xx+1][yy]=='1') { q.push((xx+1)*m+yy); grid[xx+1][yy]='0'; } if(xx-1>=0&&grid[xx-1][yy]=='1') { q.push((xx-1)*m+yy); grid[xx-1][yy]='0'; } if(yy+1<m&&grid[xx][yy+1]=='1') { q.push(xx*m+yy+1); grid[xx][yy+1]='0'; } if(yy-1>=0&&grid[xx][yy-1]=='1') { q.push(xx*m+yy-1); grid[xx][yy-1]='0'; } } } };
相关文章推荐
- Bug #19528825 "UNABLE TO PURGE A RECORD"
- uCos的内存管理
- iOS shareSDK进行第三方登录
- Bitwise AND of Numbers Range
- 修改了/etc/environment里环境变量导致登陆不了ubuntu系统
- Android开发之Intent跳转到系统应用中的拨号界面、联系人界面、短信界面
- Redis 起步
- linux查看外网IP
- Node.js REPL终端
- NYOJ 709(ZZULIOJ1481) 异 形 卵
- 插入排序-最基本的版本
- Flexslider图片轮播、文字图片相结合滑动切换效果HTML 首先在页面head部位载入jquery库文件和Flexslider插件,以及Flexslider所需的基本css样式文件。
- 关于UML图的生成
- 关于访问服务器超时的解法
- jquery 增加 tr 增加 li
- this 和 getApplicationContext Context的区别
- ant编译重设property的值
- Binary Tree Right Side View 从左边视角输出二叉树的值
- android有关网络连接的方法
- C++程序设计 - Week 2 类和对象初探