题目

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.

分析

题目描述抽象为一个图的问题,题目本质便是求连通子图的数目。

借助图的遍历算法DFS的思想,遍历该二维矩阵,每当遇到一个‘1’计数增一,同时以该坐标为起点dfs该矩阵把相邻坐标为‘1’的元素改为非1;最终计数的结果即是连通子图数量。

AC代码

class Solution {
public:
//等价于计算连通子图的个数
int numIslands(vector<vector<char>>& grid) {
if (grid.empty())
return 0; //计算该二维数组的行列
int rows = grid.size();
int cols = grid[0].size(); int count = 0;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
if (grid[i][j] == '1')
{
++count;
dfs(grid, i, j);
}
continue;
}//for
}//for
return count;
} void dfs(vector<vector<char>> &grid, int r, int c)
{
if (grid.empty())
return; //计算该二维数组的行列
int rows = grid.size();
int cols = grid[0].size(); if (r < 0 || r >= rows || c < 0 || c >= cols)
return; if (grid[r][c] == '1')
{
//改变当前元素值为非'1'
grid[r][c] = '2';
dfs(grid, r, c + 1);
dfs(grid, r + 1, c);
dfs(grid, r, c - 1);
dfs(grid, r - 1, c);
}//if
return;
}
};

GitHub测试程序源码

最新文章

  1. Oracle中较长number型数值的科学计数显示问题
  2. VS开发中的代码编写小技巧&mdash;&mdash;避免重复代码编写的几种方法
  3. dwz 在dialog里打开dialog
  4. 使用Python的yield实现流计算模式
  5. __ATTRIBUTE__ 你知多少?【转】
  6. hadoop2.2编程:mapreduce编程之二次排序
  7. 暴力求解——POJ 1321 棋盘问题
  8. android 之 百度地图
  9. oracle plsql 64位 32位连接未打开 无法解析各种错终极解决方案
  10. C++ 头文件系列(fstream)
  11. linux下载时提示请尝试移除磁盘中不需要的文件并重试,或者保存到其他位置
  12. CSS实现覆盖弹窗(效果如JQuery-UI的Dialog)
  13. code forces 436 C. Bus
  14. Android开发之监听发出的短信
  15. Struts-ValueStack和OGNL总结
  16. window编程_消息分类
  17. js&#183;&#183;&#183;DOM2动态创建节点
  18. 本地文件程序脚本上传linux系统中文乱码问题
  19. Root(hdu5777+扩展欧几里得+原根)2015 Multi-University Training Contest 7
  20. P1337 [JSOI2004]平衡点 / 吊打XXX

热门文章

  1. Linux上使用VIM进行.Net Core
  2. Zeppelin的入门使用系列之使用Zeppelin来运行Spark SQL(四)
  3. 通过代码理解Asp.net4中的几种ClientIDMode设置.
  4. 5.类型、值和变量-JavaScript权威指南笔记
  5. Android 使用RecyclerView实现多行水平分页的GridView效果和ViewPager效果
  6. 初识EditText - 自定义EditText形状
  7. SQL 事物回滚
  8. Web端 session cookies Application viewstate
  9. 免费手机号码归属地API查询接口
  10. SCOPE_IDENTITY和@@IDENTITY[转]