[Leetcode]Number of Island
来源:互联网 发布:mac如何删除文件夹 编辑:程序博客网 时间:2024/05/21 18:45
[题目]
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:
11110110101100000000
Answer: 1
Example 2:
11000110000010000011
Answer: 3
[思路]
对于grid里面遇到的“1”,利用DFS,进行搜索深入,只要是相连的,就挖出来变成0,好聪明啊。。。简直了哦。
[代码]
public class Solution { private static final int[][] DIRS = new int[][]{{1,0},{-1,0},{0,1},{0,-1}}; private static final char L = '1', W = '0'; public void dfsFill(char[][] g, int x, int y) { if (x >= 0 && x < g.length && y >= 0 && y < g[0].length && g[x][y] == L) { g[x][y] = W; for (int[] d : DIRS) dfsFill(g, x + d[0], y + d[1]); } } public int numIslands(char[][] grid) { int num = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == L) { num++; dfsFill(grid, i, j); } } } return num; }}
0 0
- [Leetcode]Number of Island
- 【Leetcode】200. Number of Island
- LeetCode: Max Area of Island
- Max Area of Island(leetcode)
- leetCode-Max Area of Island
- 【LintCode】Number of Island 岛屿的数目
- leetcode 695. Max Area of Island 解法
- leetcode 695(Max Area of Island)
- [LeetCode] Algorithms-695. Max Area of Island
- leetcode 695 Max Area of Island
- Leetcode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- LeetCode 695. Max Area of Island
- LeetCode-695. Max Area of Island
- [LeetCode] 695. Max Area of Island
- 【LeetCode】695. Max Area of Island
- [LeetCode] Number of Islands
- Leetcode-Number of Islands
- 31、df 命令
- getResources()方法读取jar包内部的文件
- windows平台下载webrtc代码和生成vs2013工程(非ninja)
- 提高 Vim 和 Shell 效率的 9 个建议
- cocos2dx解压缩文件
- [Leetcode]Number of Island
- 开始啃 Erlang 程序设计,第一口
- jdk的环境配置方法
- Happy Number
- 双机 集群 容灾 负载均衡的理解
- Hello MyBlog
- 版本控制-搭建git服务器
- 感谢陪一起走过心路历程的人
- 一次完整的HTTP事务过程分析