1. 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:

Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

解1 bfs

class Solution {
public:
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
bool valid(int x, int y, int m, int n){
if(x < 0 || x >= m || y < 0 || y >= n)return false;
return true;
}
int numIslands(vector<vector<char>>& grid) {
if(grid.size() == 0)return 0;
vector<vector<bool>> vis(grid.size(), vector<bool>(grid[0].size(), false));
int ans = 0;
for(int i = 0; i < grid.size(); ++i){
for(int j = 0; j < grid[0].size(); ++j){
if(vis[i][j] == false && grid[i][j] == '1'){
ans++;
bfs(grid, vis, i, j);
//dfs(grid, vis, i, j);
}
}
}
return ans;
}
void bfs(vector<vector<char>>& grid, vector<vector<bool>>& vis,
int x, int y){
queue<pair<int, int>>q;
q.push(make_pair(x,y));
vis[x][y] = true;
while(!q.empty()){
int tmpx = q.front().first, tmpy = q.front().second;
q.pop();
for(int i = 0; i < 4; ++i){
int tmpxx = tmpx + dx[i], tmpyy = tmpy + dy[i];
if(valid(tmpxx, tmpyy, grid.size(), grid[0].size())
&& !vis[tmpxx][tmpyy] && grid[tmpxx][tmpyy]=='1'){
q.push(make_pair(tmpxx, tmpyy));
vis[tmpxx][tmpyy] = true;
}
}
}
}
};

解2 dfs

	void dfs(vector<vector<char>>& grid, vector<vector<bool>>& vis,
int x, int y){
vis[x][y] = true;
for(int i = 0; i < 4; ++i){
int tmpx = x + dx[i], tmpy = y + dy[i];
if(valid(tmpx, tmpy, grid.size(), grid[0].size())
&& !vis[tmpx][tmpy] && grid[tmpx][tmpy] == '1'){
dfs(grid, vis, tmpx, tmpy);
}
}
}

最新文章

  1. WCF 客户端代理生成 通过SvcUtil.exe
  2. [Exchange]使用EWS托管API2.0同步邮箱
  3. [Oracle] PL/SQL学习笔记
  4. noip2006 2^k进制数
  5. 使用Android Studio搭建Android集成开发环境
  6. css选择符有哪些?哪些属性可以继承?优先级算法如何计算?内联和important哪个优先
  7. # 36氪开放日 &bull; 杭州 &bull; 11月10日 # 谈谈参会感受
  8. android sqlite操作(2)
  9. React组件测试(模拟组件、函数和事件)
  10. SaaS系列介绍之一: SaaS的前身ASP介绍
  11. [转]oracle性能调优之--Oracle 10g AWR 配置
  12. Shell中特殊的变量
  13. MVC5.0 中如何提高Controller 的优先级
  14. Hadoop Hive sql语法详解
  15. 为什么yslow用不了
  16. Find modern, interactive web-based charts for R at the htmlwidgets gallery
  17. 剑指offer前6题
  18. mySQL的表操作
  19. netty(八) netty中自带channelhandler
  20. Windows 下面 redis 发布为服务的官方方法

热门文章

  1. C#验证对象中的属性是否为空的共通方法
  2. Linux(Centos)安装git
  3. java类型转换拓展
  4. vsp配合Qt5开发,解决virtual void * __cdecl PopDialogManger::qt_metacast
  5. 【LeetCode】966. Vowel Spellchecker 解题报告(Python)
  6. ZOJ 3785:What day is that day?(数论)
  7. kotlin+springboot+mybatis-puls+mysql搭建gradle-web工程
  8. 编写Java程序,使用日期处理类实现日期的格式化输出
  9. .net core的Swagger接口文档使用教程(一):Swashbuckle
  10. Swoole 中使用 Lock 实现进程间锁