LeetCode刷题笔记——DFS(岛屿问题-200,695)-Go语言
200. 岛屿数量 中等
给你一个由 ‘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
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
的值为 ‘0’ 或 ‘1’
思路
- 我们从头遍历
grid
数组,遇到’1’就沉默(将属于这个小岛的’1’全部改为’0’) - 用递归找出所有属于这一小岛的’1’边修改为’0’
对于这样一个只有一个岛屿的二维数组我们怎样才能将属于这个岛的‘1’全部变为’0’呢?
当我们遍历到这个小岛的第一个‘1’的时候我们用一个辅助递归函数处理为‘0’并向四个方向进行延生。
func numIslands(grid [][]byte) int {
if len(grid) == 0 || len(grid[0]) == 0 {
return 0
}
res := 0
n, m := len(grid), len(grid[0])
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == '1' {
res++
solve(grid, i, j)
}
}
}
return res
}
func solve(grid [][]byte, i, j int) {
if i >= 0 && j >= 0 && i < len(grid) && j < len(grid[0]) && grid[i][j] == '1' {
grid[i][j] = '0'
solve(grid, i+1, j)
solve(grid, i, j+1)
solve(grid, i-1, j)
solve(grid, i, j-1)
}
}
695. 岛屿的最大面积 中等
给你一个大小为 m x n 的二进制矩阵 grid 。
岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
岛屿的面积是岛上值为 1 的单元格的数目。
计算并返回 grid 中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。
示例 1:
输入:grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
输出:6
解释:答案不应该是 11 ,因为岛屿只能包含水平或垂直这四个方向上的 1 。
示例 2:
输入:grid = [[0,0,0,0,0,0,0,0]]
输出:0
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
为0
或1
思路
总体思路和上一题一样就是遍历加处理
不一样的是辅助递归函数要可以统计当前的小岛的面积。为此我们最好使用全局变量来统计岛屿的面积。
func maxAreaOfIsland(grid [][]int) int {
if len(grid) == 0 || len(grid[0]) == 0 {
return 0
}
res := 0
var max = func(a, b int) int {
if a > b {
return a
}
return b
}
n, m := len(grid), len(grid[0])
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == 1 {
num = 0
solve(grid, i, j)
res = max(res, num)
}
}
}
return res
}
var num = 0
func solve(grid [][]int, i, j int) {
if i >= 0 && j >= 0 && i < len(grid) && j < len(grid[0]) && grid[i][j] == 1 {
grid[i][j] = 0
num++
solve(grid, i+1, j)
solve(grid, i, j+1)
solve(grid, i-1, j)
solve(grid, i, j-1)
}
}