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.
这道题主要是考察采用队列的宽度(广度)遍历,类似水波涟漪扩散,还有标记的技巧。
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
def help(i ,j ,grid ,queue):
if i<0 or i >= len(grid) or j < 0 or j >= len(grid[0]):
return
elif grid[i][j] == 1:
queue.insert(0, [i, j])
grid[i][j] = -1
queue = []
res = []
maxarea = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == 1:
queue.insert(0, [i, j])
grid[i][j] = -1
sum = 0
while (len(queue) > 0):
a, b = queue[-1][0], queue[-1][1]
sum += 1
queue.pop()
help(a, b- 1, grid, queue)
help(a, b + 1, grid, queue)
help(a - 1, b, grid, queue)
help(a + 1, b, grid, queue)
if sum>maxarea:
maxarea = sum
return maxarea
类似题目:
200. Number of Islands
Given a 2d grid map of '1’s (land) and '0’s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def help(i ,j ,grid ,queue):
if i<0 or i >= len(grid) or j < 0 or j >= len(grid[0]):
return
elif grid[i][j] == "1":
queue.insert(0, [i, j])
grid[i][j] = -1
queue = []
res = []
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "1":
queue.insert(0, [i, j])
grid[i][j] = -1
sum = 0
while (len(queue) > 0):
a, b = queue[-1][0], queue[-1][1]
sum += 1
queue.pop()
help(a, b- 1, grid, queue)
help(a, b + 1, grid, queue)
help(a - 1, b, grid, queue)
help(a + 1, b, grid, queue)
res.append(sum)
return len(res)