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.
在矩阵中找相连起来的最大的1s串(上下左右) 并计数返回
自己写的dfs:
def finded(x, y, nums):
ans2 = 1
if nums[x][y] == 0:
return 0
nums[x][y] = 0
if x - 1 >= 0:
ans2 += finded(x - 1, y, nums)
if x + 1 < len(nums):
ans2 += finded(x + 1, y, nums)
if y + 1 < len(nums[0]):
ans2 += finded(x, y + 1, nums)
if y - 1 >= 0:
ans2 += finded(x, y - 1, nums)
return ans2
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
r = len(nums)
c = len(nums[0])
ans = 0
for i in range(r):
for j in range(c):
if nums[i][j] == 0:
continue
res = finded(i, j, nums)
if ans < res:
ans = res
return ans
题解中的DfS算法:
class Solution(object):
def maxAreaOfIsland(self, grid):
seen = set()
def area(r, c):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])
and (r, c) not in seen and grid[r][c]):
return 0
seen.add((r, c))
return (1 + area(r + 1, c) + area(r - 1, c) +
area(r, c - 1) + area(r, c + 1))
return max(area(r, c)
for r in range(len(grid))
for c in range(len(grid[0])))