題目
給定一個包含了一些 0 和 1的非空二維數(shù)組 grid , 一個 島嶼 是由四個方向 (水平或垂直) 的 1 (代表土地) 構(gòu)成的組合贾费。你可以假設(shè)二維矩陣的四個邊緣都被水包圍著。
找到給定的二維數(shù)組中最大的島嶼面積彰触。(如果沒有島嶼,則返回面積為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]]
對于上面這個給定矩陣應(yīng)返回 6况毅。注意答案不應(yīng)該是11,因為島嶼只能包含水平或垂直的四個方向的‘1’尔艇。
示例二
[[0,0,0,0,0,0,0,0]]
對于上面這個給定的矩陣, 返回 0尔许。
注意: 給定的矩陣grid
的長度和寬度都不超過 50。
分析與解答
這道題目和前面做過的python-數(shù)據(jù)結(jié)構(gòu) 島嶼的個數(shù) 深度優(yōu)先 廣度優(yōu)先 兩種解答是一個一模一樣的題目终娃,主要是可以使用隊列來進行一個廣度優(yōu)先查詢味廊。
class Solution:
def maxAreaOfIsland(self, grid) -> int:
if not grid:
return 0
if isinstance(grid[0], bool) or isinstance(grid[0], int):
return 1 if grid[0] else 0
ilsand_list = [0] # 排除當(dāng)沒有島嶼的時候,執(zhí)行max函數(shù)出錯
m, n = len(grid), len(grid[0]) # m代表行棠耕, n代表列
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = "0"
size_of_island, grid = self.get_size_of_island(i, j, grid) # 利用隊列(廣度優(yōu)先查詢)余佛,將島嶼所在位置全部求出并且獲得島嶼大小
ilsand_list.append(size_of_island)
return max(ilsand_list)
def get_size_of_island(self, i, j, grid):
size_of_island = 1 # 能走到這邊說明這個島嶼的最小初始面積為1
m, n = len(grid), len(grid[0]) # m代表行, n代表列
use_list = [[i, j], ]
while len(use_list):
i, j = use_list.pop(0)
if i > 0:
if grid[i - 1][j] == 1:
grid[i - 1][j] = "0"
use_list.append([i - 1, j])
size_of_island += 1
if i < m - 1:
if grid[i + 1][j] == 1:
grid[i + 1][j] = "0"
use_list.append([i + 1, j])
size_of_island += 1
if j > 0:
if grid[i][j - 1] == 1:
grid[i][j - 1] = "0"
use_list.append([i, j - 1])
size_of_island += 1
if j < n - 1:
if grid[i][j + 1] == 1:
grid[i][j + 1] = "0"
use_list.append([i, j + 1])
size_of_island += 1
return size_of_island, grid
if __name__ == '__main__':
s = Solution()
g0 = []
# g1 = [["0"]]
# g2 = [["1", "1", "0", "0", "0"],
# ["1", "1", "0", "0", "0"],
# ["0", "0", "1", "0", "0"],
# ["0", "0", "0", "1", "1"]]
# for g in [g0, g1, g2]:
# print(s.numIslands(g))
a = [[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1]]
print(s.maxAreaOfIsland(a))