算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 岛屿数量,我们先来看题面:
https://leetcode-cn.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.
题意
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
解题
我们遍历整个二维数组,当我们遇到为'1'的,我们将其相邻的所有‘1’重置为‘0’,即将这一块岛全部都变为海水然后再去遍历数组剩下的部分。遇到一个岛屿的第一标‘1’的cnt加1。
class Solution {
public int numIslands(char[][] grid) {
int cnt = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == '1') {
depthSearch(grid,i,j);
cnt++;
}
}
}
return cnt;
}
public void depthSearch(char[][] grid, int i, int j) {
if (grid == null ||(i<0 || i >= grid.length) ||( j<0 || j >= grid[i].length)) {
return;
}
if (grid[i][j] != '1') {
return;
}
grid[i][j] = '0';
depthSearch(grid, i + 1, j) ;
depthSearch(grid, i - 1, j) ;
depthSearch(grid, i, j + 1) ;
depthSearch(grid, i, j - 1);
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: