topic
Given a two-dimensional array of non-null grid number 0 and 1, is an island formed of a combination of four directions (horizontal or vertical) 1 (representing the land). You can assume that the four edges of the two-dimensional matrix are surrounded by water.
Find a given two-dimensional array in the largest island in the area. (If there are no islands, the area is returned to 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]]
For the above should return the given matrix 6. Note that the answer should not be 11, since the islands comprise only four horizontal or vertical direction is '1'.
Example 2:
[[0,0,0,0,0,0,0,0]]
For the above given matrix, 0 is returned.
Note: The length and width of the given grid matrix is not more than 50.
answer
A typical search topic , depth-first and breadth-first can be. (Relatively simple, the idea is not recorded)
1, depth-first DFS, recursively. Time: O (mn), Space: O (mn) 2, breadth-first bfs, with the queue. Time: O (mn), Space: O (mn)
# 深搜
class Solution:
def __init__(self):
self.a = []
self.book = []
self.next = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
]
self.m = 0
self.n = 0
self.max = 0
def maxAreaOfIsland(self, grid) -> int:
if not grid:
return 0
self.a, self.m, self.n = grid, len(grid), len(grid[0])
self.book = [
[0 for _ in range(self.n)] for _ in range(self.m)
]
max = 0
for i in range(self.m):
for j in range(self.n):
if self.a[i][j] == 1:
self.max = 0
self.book[i][j] = 1
self.max += 1
self.dfs(i, j)
if self.max > max:
max = self.max
return max
def dfs(self, x, y):
for i in range(4):
tx = x + self.next[i][0]
ty = y + self.next[i][1]
if tx >= 0 and ty >= 0 and tx < self.m and ty < self.n and self.book[tx][ty] == 0 and self.a[tx][ty] == 1:
self.max += 1
self.book[tx][ty] = 1
self.dfs(tx, ty)
# 不取消标记,只走一次即可
s = Solution()
ans = s.maxAreaOfIsland([[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]])
print(ans)
# 6