经典算法题之Number of Islands
来源:互联网 发布:php换行代码 编辑:程序博客网 时间:2024/06/14 17:19
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:int dfs(vector<vector<char> >& grid, int row, int col) {grid[row][col]='x';if(((row+1) < grid.size()) && grid[row+1][col]=='1') {//grid[row+1][col]='0';dfs(grid, row+1, col);}if(((col+1) <grid[0].size()) && grid[row][col+1]=='1') {//grid[row][col+1]='0';dfs(grid, row, col+1);}/*以下两种情况刚开始忽略掉了,当出现 100 111 101 或 010 111 111 时就会得到错误答案 */if(row-1>=0 && grid[row-1][col]=='1') {dfs(grid, row-1, col);}if(col-1>=0 && grid[row][col-1]=='1') {dfs(grid, row, col-1);}return 0;} int numIslands(vector<vector<char> >& grid) { if(grid.empty()||grid[0].empty())return 0;int count=0;for(int i=0; i<grid.size(); ++i) {for(int j=0; j<grid[0].size(); ++j) {if(grid[i][j]=='1') {dfs(grid, i, j);++count;}}}return count; }};
0 0
- 经典算法题之Number of Islands
- 算法题——Number of Islands(C++)BFS
- 【LeetCode-面试算法经典-Java实现】【200-Number of Islands(岛的数目)】
- Medium 200题 Number of Islands
- Number of Islands
- Number of Islands
- Number of Islands
- [LeetCode] Number of Islands
- Leetcode-Number of Islands
- Number of Islands
- Leetcode Number of Islands
- [LeetCode]Number of Islands
- Number of Islands
- Number of Islands
- [leetcode]Number of Islands
- [leetcode] Number of Islands
- leetcode Number of Islands
- leetcode:Number of Islands
- leetcode : count and say
- freeshell探索日记-预装软件
- noexcept异常说明
- android常见面试题与我自己的回答 (二)
- 深入理解GC ——MinorGC\MajorGC\FullGC
- 经典算法题之Number of Islands
- 判断回文字符串.
- poj 2251
- bug总结
- 开启Objective-C
- OC中实例变量可见度、setter、getter方法和自定义初始化方法
- OC中的NSNumber、NSArray、NSString的常用方法
- copy_to_user、copy_from_user 分析
- OC中NSDictionary、NSSet得常用方法