Given a non-empty two-dimensional array grid consisting of 0s and 1s, used to represent a map of ocean islands.
An island is a combination of adjacent 1s (representing land), where "adjacent" requires that two 1s must be adjacent in the horizontal or vertical direction. You can assume that all four edges of the grid are surrounded by 0s (for water).
Find the largest island area in the given 2D array. If there are no islands, the area is returned as 0.
Example 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
Explanation: 6 should be returned for the given matrix above. Note that the answer should not be 11, because islands can only contain 1s in four directions, either horizontally or vertically.
Example 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] is either 0 or 1
Problem solving ideas
- Traverse and record the visited and unvisited islands; if it is an island, set the state to visited;
- Traverse up, down, left and right respectively, record the number of islands, and set the current island as visited;
- Update island records based on large islands
Problem solving code and its comments
/**
* @param {number[][]} grid
* @return {number}
*/
var maxAreaOfIsland = function (grid) {
let col = grid.length,row = grid[0].length,max=0; //行、列
//未访问过的岛屿为1,访问过的岛屿为0
let matrix = [...Array(col)].fill(0).map(()=> [...Array(row)].fill(1))
let dfs = (i,j)=>{
//边界
if(i<0 || i>=col || j<0 || j>=row) return 0;
let ret=0;
let temp = matrix[i][j] //是否为岛屿
matrix[i][j] = 0 //访问过的岛屿标记为 0
if(grid[i][j] && temp){
ret+=dfs(i+1,j) //下
ret+=dfs(i-1,j) //上
ret+=dfs(i,j+1) //右
ret+=dfs(i,j-1) //左
ret++
}
return ret
}
for(let i=0;i<col;i++){
for(let j=0;j<row;j++){
if(grid[i][j]===1){
//更新岛屿记录
max = Math.max(max,dfs(i,j))
}
}
}
return max
};
Summary [DFS]
深度优先搜索算法(Depth-First-Search)
: is an algorithm for traversing or searching a tree or graph. Traverse the nodes of the tree along the depth of the tree, searching for branches of the tree as deep as possible. When the edges of the node v have been explored or the node does not meet the conditions during the search, the search will backtrack to the starting node of the edge where the node v is found. The whole process is repeated until all nodes are visited. Depth-first search is implemented based on stacks, which are first in and then out.
DFS main steps
The main steps:
1. Build a recursive function, the function parameters should at least include the parameters required by the problem
2. Find the boundary, first list the conditions for the end of the recursion in the recursive function, that is, meet the requirements or exceed the scope
3. Then list all possible paths of movement or change
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。