广度优先搜索
Python代码
def bfs(x, y, n, m):
queue = [(x, y)]
hh, tt = 0, 0
cnt = 1
move = [(0, 1), (1, 0), (-1, 0), (0, -1)]
while hh <= tt:
sx, sy = queue[hh]
hh += 1
for i, j in move:
nx, ny = sx + i, sy + j
if 0 <= nx < n and 0 <= ny < m and grids[nx][ny] == '.':
queue.append((nx, ny))
tt += 1
cnt += 1
grids[nx][ny] = '-'
return cnt
while True:
m, n = map(int, input().split())
if m == 0 and n == 0: break
grids = []
for _ in range(n):
grids.append(list(input()))
for i in range(n):
for j in range(m):
if grids[i][j] == '@':
x, y = i, j
break
res = bfs(x, y, n, m)
print(res)
个人博客题解:
https://blowfire.blog.csdn.net/article/details/112507044