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
Example 2:
Input:
11000
11000
00100
00011
Output: 3
具體的思路可以見我的博客園的博客:https://www.cnblogs.com/Weixu-Liu/p/10712642.html
在這個題中,我用python重新寫B(tài)FS,在寫B(tài)FS中,可以新建立一個列表,把位置下標(biāo)用元組表示,加到列表中就行。
python代碼:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
sum = 0
q = []
m = len(grid)
if m == 0:
return 0
n = len(grid[0])
dx = [0,0,1,-1]
dy = [1,-1,0,0]
for r in range(m):
for c in range(n):
if grid[r][c] == '1':
grid[r][c] == '0'
q.append((r,c))
while len(q):
Q = q.pop(0)
index_r = Q[0]
index_c = Q[1]
for i in range(4):
x = index_r + dx[i]
y = index_c + dy[i]
if x >= 0 and x < m and y >= 0 and y < n and grid[x][y] == '1':
grid[x][y] = '0'
q.append((x,y))
sum += 1
return sum
PS
不能寫grid[r, c] == '0',這個是在NumPy中的array數(shù)組上能用的。。。在列表就行不通了,o(╯□╰)o