【LeetCode】200. Number of Islands 岛屿数量(Medium)(JAVA)
题目地址: https://leetcode.com/problems/number-of-islands/
题目描述:
Given an m x n 2d grid map of '1’s (land) and '0’s (water), return 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:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is ‘0’ or ‘1’.
题目大意
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
解题方法
- 遍历所有的元素,如果为 ‘1’ 不断扩张,知道遇不到 ‘1’ 为止;同时把遇到的 ‘1’ 置为 ‘0’ 防止重复遍历
class Solution {
public int numIslands(char[][] grid) {
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '0') continue;
res++;
nH(grid, i, j);
}
}
return res;
}
int[][] rev = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public void nH(char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') return;
grid[i][j] = '0';
for (int k = 0; k < rev.length; k++) {
nH(grid, i + rev[k][0], j + rev[k][1]);
}
}
}
执行耗时:3 ms,击败了36.75% 的Java用户
内存消耗:40.7 MB,击败了94.09% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg)