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
感觉图形有点像扫雷哈哈。
这道题是我在BFS分类里找到的,不过BFS目前的方法会超时,等待以后做DFS时候再更新DFS算法。
BFS算法的思想就是建立一个deque()(双边队列),每次遇到第一个"1"以后,把它的(r,c)加入的队列。
把队列最左面的出列,先把他修改为"0",然后再去找他的上下左右,如果有"1",就属于同一个island,也加入到队列中,这样重复操作即可。
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if len(grid)==0: return 0
row, col = len(grid), len(grid[0])
count = 0
queue = collections.deque()
steps = [[-1,0],[1,0],[0,-1],[0,1]]
for i in range(row):
for j in range(col):
if grid[i][j]=='1' :
count+=1
queue.append([i,j])
while queue:
x,y = queue.popleft()
grid[x][y] = '0'
for step in steps:
if 0<=x+step[0]<row and 0<=y+step[1]<col and grid[x+step[0]][y+step[1]] == '1':
queue.append([x+step[0] ,y+step[1]])
return count
等做到DFS来填坑