Number of Islands - leetcode
2015-10-03 14:06
302 查看
原题链接
题目:
思路:
code
题目:
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/bfs来求解. (如果一个图是全连通图, 那么dfs/bfs可一次遍历完该图)
code
class Solution { public: bool check(int m, int n, int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; } void dfs(vector<vector<char>>& grid, int m, int n, int x, int y) { if(!check(m, n, x, y)) return; if(grid[x][y] != '1') return; // set statue: visited grid[x][y] = 'v'; dfs(grid, m, n, x - 1, y); dfs(grid, m, n, x + 1, y); dfs(grid, m, n, x, y - 1); dfs(grid, m, n, x, y + 1); } int numIslands(vector<vector<char>>& grid) { if(grid.size() == 0) return 0; int m = grid.size(); int n = grid[0].size(); int cnt = 0; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { // if grid[i][j] has been not visited and is equal to '1', // then dfs if(grid[i][j] == '1') { dfs(grid, m, n, i, j); cnt++; } } } return cnt; } };
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem