【Leetcode】200. Number of Island
来源:互联网 发布:unity3d awake 编辑:程序博客网 时间:2024/05/29 16:36
Description:
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:
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
思路:
本题需要判断二维数组中相连的’1’的块数,这里可以直观地使用DFS来找出所有块。从左上的起始点出发,对其上下左右4个点进行判断,如果是’1’且在范围内那么就继续搜寻下去,否则就什么都不做。另外,为了对已经搜寻过的点进行标记,同时最大程度节省空间,可以直接在原二维数组中操作,将访问过的’1’变为’0’。每次成功完成一次连续的搜寻,则count++,最后便可以找出结果。
以下是使用C++的实现过程:
class Solution {public: int numIslands(vector<vector<char>>& grid) { if(grid.size()==0) return 0; int count=0; for(int i=0;i<grid.size();i++){ for(int j=0;j<grid[0].size();j++){ if(grid[i][j] == '1'){ dfs(grid, i, j); count++; } } } return count; } void dfs(vector<vector<char> >& grid, int i, int j){ if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j]!='1') return; grid[i][j] = '0'; dfs(grid,i+1,j); dfs(grid,i-1,j); dfs(grid,i,j+1); dfs(grid,i,j-1); }};
阅读全文
0 0
- 【Leetcode】200. Number of Island
- [Leetcode]Number of Island
- LeetCode: Max Area of Island
- Max Area of Island(leetcode)
- leetCode-Max Area of Island
- 【LintCode】Number of Island 岛屿的数目
- [LeetCode]200.Number of Islands
- LeetCode 200. Number of Islands
- [leetcode] 200.Number of Islands
- 【leetcode】 200. Number of Islands
- [leetcode] 200. Number of Islands
- Leetcode 200. Number of Islands
- 200. Number of Islands LeetCode
- leetcode 200. Number of Islands
- LeetCode 200. Number of Islands
- leetcode.200. Number of Islands
- LeetCode 200. Number of Islands
- LeetCode-200.Number of Islands
- 部署描述文件web.xml解析(五) 声明过滤器
- 【Struts2】Session的获取
- Windows10 和 Ubuntu 16.04 双系统 系统时间不统一解决
- 关于开发工具不能找到系统中已经存在的字体
- swift 基础学习回顾(一)
- 【Leetcode】200. Number of Island
- NYOJ 255
- llinux文件编程2
- mt4
- JavaScript 深拷贝 & 浅拷贝
- [读书笔记]python爬虫-scrapy安装过程常见问题及解决方法
- Mac文件系统
- 缓存淘汰算法之LRU
- Unity常用插件之DoTween(一)