题目地址:https://leetcode.com/problems/max-area-of-island/description/
题目(岛的最大区域)
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)
Example 1:
[[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]]
Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.
Example 2:
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Note: The length of each dimension in the given grid does not exceed 50.
分析
- 利用DFS求解,关于DFS详细解释可以查询资料
- 深度优先搜索算法(英语:Depth-First-Search,简称DFS)是一种用于遍历或搜索树或图的算法。沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所在边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。属于盲目搜索。
代码
class Solution {
func maxAreaOfIsland(_ grid: [[Int]]) -> Int {
var array = grid
var maxArea = 0
for i in 0..<grid.count {
for j in 0..<grid[0].count {
if grid[i][j] == 1 {
maxArea = max(maxArea, dfs(&array, i: i, j: j))
}
}
}
return maxArea
}
//dfs的实现,因为要更改数组,所以这里参数是inout类型
func dfs(_ grid:inout [[Int]], i: Int, j: Int) -> Int {
//判断是否越界和数字是否为0,这个是递归结束的条件
if i < 0 || i >= grid.count || j < 0 || j >= grid[0].count || grid[i][j] == 0 {
return 0
}
var temMaxArea = 1
grid[i][j] = 0 //遍历后的置为0
//递归查询上下左右四个
temMaxArea = temMaxArea + dfs(&grid, i: i-1, j: j) + dfs(&grid, i: i + 1, j: j) + dfs(&grid, i: i, j: j - 1) + dfs(&grid, i: i, j: j + 1)
return temMaxArea
}
}