LeetCode OJ:Number of Islands(孤岛计数)
2015-12-08 20:21
316 查看
Given a 2d grid map of
Example 1:
Answer: 1
Example 2:
Answer: 3
计算孤岛的数量,注意上下左右为0就是孤岛,孤岛可以很大,grid范围以外的都算是water。代码如下所示:
'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
计算孤岛的数量,注意上下左右为0就是孤岛,孤岛可以很大,grid范围以外的都算是water。代码如下所示:
class Solution { public: int numIslands(vector<vector<char>>& grid) { int count = 0; if(!grid.size() || !grid[0].size()) return count; int row = grid.size(); int col = grid[0].size(); for(int i = 0; i < row; ++i){ for(int j = 0; j < col; ++j){ if(grid[i][j] == '1'){ dfs(grid, i, j); count++; } } } return count; } void dfs(vector<vector<char>> & grid, int x, int y) { if(grid[x][y] == '1') grid[x][y] = 'X'; else return; dfs(grid, x+1, y); dfs(grid, x-1, y); dfs(grid, x, y+1); dfs(grid, x, y0); } };
相关文章推荐
- 数组链表下标指针map list
- Centos root权限的变化
- Codeforces Round #105 (Div. 2) 148C Terse princess(脑洞)
- 一些算法书籍
- fs_initcall、early_initcall、__init宏
- [LeetCode]Decode Ways
- 孤华暗香的Python Spider,Updating
- 把图片变为圆形的方法(QQ头像)
- php 给图片添加水印
- php源码分析之base64_encode函数
- 双系统给ubuntu增加分区
- A计划(bfs)
- Launcher3源码分析 — 数据加载过程
- 关于“静态变量不能跨函数使用”的一个疑问
- greendao->报错:java.lang.NoClassDefFoundError: database.dao.DaoMaster
- ArrayAdapter的简单使用
- 使用 MNIST 图像识别数据集
- 20151208--批处理
- js中innerText,innerHTML的用法
- Mac平台重新设置MySQL的root密码