200. Number of Islands
2016-04-20 00:13
399 查看
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
方法一:用并查集(写的比较长,不够简洁,用时24ms)
方法2:DFS(参考讨论,用时12ms)
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
方法一:用并查集(写的比较长,不够简洁,用时24ms)
vector<int>f; int find(int k) { if(f[k]==-1) return k; else return f[k]=find(f[k]); } void fun(int a,int b) { int fa,fb; fa=find(a); fb=find(b); if(fa!=fb) f[fa]=fb; } int numIslands(vector<vector<char> >& grid) { int n=grid.size(); if(n==0) return 0; int m=grid[0].size(); f.resize(n*m,-1); vector<int>point; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j]=='1') { int p=i*m+j; point.push_back(p); if(i>0&&grid[i-1][j]=='1') fun(p-m,p); if(i<n-1&&grid[i+1][j]=='1') fun(p+m,p); if(j>0&&grid[i][j-1]=='1') fun(p-1,p); if(j<n-1&&grid[i][j+1]=='1') fun(p+1,p); } } } set<int>s; for(int i=0;i<point.size();i++) { int tmp=find(point[i]); s.insert(tmp); } return s.size(); }
方法2:DFS(参考讨论,用时12ms)
void eliminate(vector<vector<char> >&grid,int row,int col) { if(row < 0 || col < 0 || row == grid.size() || col == grid[row].size()) return ; if(grid[row][col] == '1') { grid[row][col] = '0'; eliminate(grid, row - 1, col); eliminate(grid, row + 1, col); eliminate(grid, row, col - 1); eliminate(grid, row, col + 1); } return ; } int numIslands(vector<vector<char> >& grid) { int n=grid.size(); if(n==0) return 0; int m=grid[0].size(); int count=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(grid[i][j]=='1') { count++; eliminate(grid,i,j); } } } return count; }
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- C 语言实现迷宫 DFS算法
- 1611:The Suspects
- 一幅图弄清DFT与DTFT,DFS的关系
- HDFS---Namenode
- HDFS ---- Services startup
- POJ1523 SPF dfs
- HDU-1213-How Many Tables
- poj1731 Orders dfs
- Surrounded Regions
- Binary Tree Zigzag Level Order Traversal,Restore IP Addresses,Word Search,Simplify Path
- Longest Consecutive Sequence,Distinct Subsequences,Interleaving String,Scramble String
- DFS基础(1)