Number of Islands问题及解法
来源:互联网 发布:伯明翰 知乎 编辑:程序博客网 时间:2024/05/18 18:43
问题描述:
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.
示例:
11110
11010
11000
00000
Answer: 1
11000
11000
00100
00011
Answer: 3
问题分析:
分析题意可知,我们只需要把’1‘的连通区域的个数求解出来即可,这里采用深度优先遍历求解。
过程详见代码:
class Solution {public: int numIslands(vector<vector<char>>& grid) {int m = grid.size(); if(!m) return 0;int n = grid[0].size();int count = 2;for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){if (grid[i][j] == '1'){bl(grid, count, i, j, m, n);count++;}}}return count - 2;}void bl(vector<vector<char>>& grid, int count, int i, int j, int m, int n){grid[i][j] = (char)('0' + count);if (j + 1 < n && grid[i][j + 1] == '1') bl(grid, count, i, j + 1, m, n);if (i + 1 < m && grid[i + 1][j] == '1') bl(grid, count, i + 1, j, m, n);if (j - 1 >= 0 && grid[i][j - 1] == '1') bl(grid, count, i, j - 1, m, n);if (i - 1 >= 0 && grid[i - 1][j] == '1') bl(grid, count, i - 1, j, m, n);}};
阅读全文
0 0
- Number of Islands问题及解法
- Number of Boomerangs问题及解法
- Letter Combinations of a Phone Number问题及解法
- Number of Segments in a String问题及解法
- Minimum Number of Arrows to Burst Balloons问题及解法
- 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
- 现在在做电子地图的一个小项目
- Myeclipse项目添加spring支持,使包名有提示的方法。
- 军训队列
- adb server is out of date. killing问题
- Linux中fork()函数详解
- Number of Islands问题及解法
- JAVA开发的23种设计模式之 --- 桥接模式
- 使用FileZilla连接时超时,无法连接到服务器
- 正则表达式随笔小记(二)
- java 单列集合总结
- Go语言学习笔记(五)方法
- Linux:命令执行控制&&与||
- R语言-数据库连接与使用
- C++中多次循环输出一个文件内的每行信息