Max Area of Island
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 深度搜索
遇到一个1就加入stack,同时把neighbor也加进来,trace一个就把那个值变成0
注意点:在加neighbor的时候有可能会重复加,所以每次check完neighbor要立刻set值为0
Solution:
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
area = 0
x = len(grid)
y = len(grid[0])
def addNeighbor(myStack, i, j):
if i-1 >= 0 and grid[i-1][j] == 1:
grid[i-1][j] = 0
myStack.append([i-1, j])
if i+1 < x and grid[i+1][j] == 1:
grid[i+1][j] = 0
myStack.append([i+1, j])
if j - 1 >= 0 and grid[i][j-1] == 1:
grid[i][j-1] = 0
myStack.append([i, j-1])
if j + 1 < y and grid[i][j+1] == 1:
grid[i][j+1] = 0
myStack.append([i, j+1])
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
local_area = 0
grid[i][j] = 0
stack = []
stack.append([i,j])
while stack:
newPair = stack.pop()
grid[newPair[0]][newPair[1]] = 0
addNeighbor(stack, newPair[0], newPair[1])
local_area += 1
area = max(area, local_area)
return area
Time complexity: O(n*m) n is length of grid, m is length of grid[0]