简单BFS,现在对最基本的BFS应该理解了,感觉比DFS简单多了。。
import sys
stdin = sys.stdin
def get_adj(a, i, j):
r = []
w = len(a[0])
h = len(a)
if i - 1 >= 0 and a[i - 1][j] == '.':
r.append([i - 1, j])
if i + 1 < h and a[i + 1][j] == '.':
r.append([i + 1, j])
if j - 1 >= 0 and a[i][j - 1] == '.':
r.append([i, j - 1])
if j + 1 < w and a[i][j + 1] == '.':
r.append([i, j + 1])
return r
while(True):
wh = stdin.readline().strip().split()
w = int(wh[0])
h = int(wh[1])
if(w == 0 and h == 0):
break
a = []
for i in range(0, h):
s = stdin.readline().strip()
index = s.find('@')
if index >= 0:
bi = i
bj = index
a.append(list(s))
queue = [[bi, bj]]
a[bi][bj] = '#'
total = 1
while(len(queue) > 0):
point = queue[0]
del queue[0]
adjs = get_adj(a, point[0], point[1])
for adj in adjs:
a[adj[0]][adj[1]] = '#'
queue.append(adj)
total += 1
print total