leetcode-Number of Islands
来源:互联网 发布:list转换成byte数组 编辑:程序博客网 时间:2024/06/08 06:20
一、题目描述
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
二、思路分析只需要利用bfs遍历一遍,遍历原则是,遇到为1时将其周围的1都设为0,其中遇到1的数量就是岛的数量。
三、代码
class Solution {public: int numIslands(vector<vector<char> >& grid) { int row = grid.size(); if (row == 0) { return 0; } int col = grid[0].size(); if (col == 0) { return 0; } int count = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (grid[i][j] == '1') { bfs(grid, row, col, i, j); count++; } } } return count; }private:void bfs(vector<vector<char> >& grid, int row, int col, int i, int j) {if (i < 0|| j < 0|| i >= row|| j >= col||grid[i][j] == '0') {return;} grid[i][j] = '0';bfs(grid, row, col, i+1, j);bfs(grid, row, col, i-1, j);bfs(grid, row, col, i, j-1);bfs(grid, row, col, i, j+1);}};
阅读全文
0 0
- [LeetCode] Number of Islands
- Leetcode-Number of Islands
- Leetcode Number of Islands
- [LeetCode]Number of Islands
- [leetcode]Number of Islands
- [leetcode] Number of Islands
- leetcode Number of Islands
- leetcode:Number of Islands
- [leetcode] Number of Islands
- [LeetCode] Number of Islands
- LeetCode:Number of Islands
- Leetcode: Number of Islands
- 【LeetCode】Number of Islands
- [leetcode] Number of Islands
- leetcode--Number of Islands
- Leetcode|Number of Islands
- Number of Islands -- leetcode
- LeetCode Number of Islands
- 【Scikit-Learn 中文文档】特征选择
- Exception和File/day_17
- 【C#】ConfigurationSettings.AppSettings 已过时
- 类的一般形式
- 在linux环境下编译运行OpenCV程序的两种方法
- leetcode-Number of Islands
- 【Scikit-Learn 中文文档】特征选择
- 利用程序写caffe协议:同名层
- 错误笔记:写项目时用PreparedStatement向数据库中插入数据报游标不足错误
- C#:另一种判断质数的代码,并统计数量
- 被static修饰的成员变量可以被修改吗
- [基础题] 6.(*)按如下要求编写Java程序: (1)编写一个接口:OneToN,只含有一个方法int dispose(int n)
- 习题6.11
- numpy.logspace用法