給你乙個由 '1'(陸地)和 '0'(水)組成的的二維網格,請你計算網格中島嶼的數量。
島嶼總是被水包圍,並且每座島嶼只能由水平方向和/或豎直方向上相鄰的陸地連線形成。
此外,你可以假設該網格的四條邊均被水包圍。
示例 1:
輸入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]輸出:1
示例 2:
輸入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]輸出:3
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值為 '0' 或 '1'
class solution:
def numislands(self, grid: list[list[str]]) -> int:
def dfs(grid,r,c):
grid[r][c]=0
nr=len(grid)
nc=len(grid[0])
for x, y in [(r-1,c),(r+1,c),(r,c-1),(r,c+1)]:
if 0<=xdfs(grid,x,y)
nr=len(grid)
if nr==0:return 0
nc=len(grid[0])
res=0
for i in range(nr):
for j in range(nc):
if grid[i][j]=='1':
res+=1
dfs(grid,i,j)
return res
LeetCode 200 島嶼數量
給定乙個由 1 陸地 和 0 水 組成的的二維網格,計算島嶼的數量。乙個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連線而成的。你可以假設網格的四個邊均被水包圍。示例 1 輸入 11110 11010 11000 00000輸出 1 示例 2 輸入 11000 11000 00100 00...
leetcode200 島嶼數量
可以遍歷矩陣中的每個位置,如果遇到1就將與其相連的一片1都感染成2 dfs 並自增島數量。class solution object def numislands self,grid type grid list list str rtype int res 0 if not grid return...
leetcode 200 島嶼數量
給定乙個由 1 陸地 和 0 水 組成的的二維網格,計算島嶼的數量。乙個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連線而成的。你可以假設網格的四個邊均被水包圍。示例 1 輸入 11110 11010 11000 00000 輸出 1思路 線性掃瞄整個二維網格,如果乙個結點包含 1,則以其...