We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
[[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’。
[[0,0,0,0,0,0,0,0]] 对于上面这个给定的矩阵, 返回 0。
给定的矩阵grid 的长度和宽度都不超过 50。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/max-area-of-island
根据题意,如果一个元素为1,我要判断它周围是否为1,然后才能确定面积。可以联想到深度优先搜索。
func maxAreaOfIsland(grid [][]int) int { var area int row := len(grid) column := len(grid[0]) for i := 0; i < row; i++ { for j := 0; j < column; j++ { if grid[i][j] == 1 { t := dfs(grid, i, j) if t > area { area = t } } } } return area } func dfs(grid [][]int, row int, column int) int { if row < 0 || row >= len(grid) || column < 0 || column >= len(grid[0]) || grid[row][column] == 0 { return 0 } t := 1 // 这里赋值为0,是因为骂我们这里有递归,如果不赋值为0的话,会栈溢出 grid[row][column] = 0 // 左边 t += dfs(grid, row, column-1) // 上边 t += dfs(grid, row-1, column) // 右边 t += dfs(grid, row, column+1) // 下边 t += dfs(grid, row+1, column) return t }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例 1:
示例 2:
注意:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
解答
根据题意,如果一个元素为1,我要判断它周围是否为1,然后才能确定面积。可以联想到深度优先搜索。
The text was updated successfully, but these errors were encountered: