计蒜客 T1212 仙岛求药 python题解
题目链接
问题描述:
少年李逍遥的婶婶病了,王小虎介绍他去一趟仙灵岛,向仙女姐姐要仙丹救婶婶。叛逆但孝顺的李逍遥闯进了仙灵岛,克服了千险万难来到岛的中心,发现仙药摆在了迷阵的深处。迷阵由 M×N个方格组成,有的方格内有可以瞬秒李逍遥的怪物,而有的方格内则是安全。现在李逍遥想尽快找到仙药,显然他应避开有怪物的方格,并经过最少的方格,而且那里会有神秘人物等待着他。现在要求你来帮助他实现这个目标。
输入格式:
输入有多组测试数据. 每组测试数据以两个非零整数 M 和 N 开始,两者均不大于20。M 表示迷阵行数, N 表示迷阵列数。接下来有 M 行, 每行包含N个字符,不同字符分别代表不同含义:
1)‘@’:少年李逍遥所在的位置;
2)‘.’:可以安全通行的方格;
3)‘#’:有怪物的方格;
4)‘’:仙药所在位置。
输出格式:
输出一行,该行包含李逍遥找到仙药需要穿过的最少的方格数目(计数包括初始位置的方块)。如果他不可能找到仙药, 则输出 −1。
【输入样例】
8 8
.@##…#
#…#.#
#.#.##…
…#.###.
#.#…#.
…###.#.
…#.…
.#…###
6 5
.*.#.
.#…
…##.
…
.#…
…@
9 6
.#…#.
.#.*.#
.####.
…#…
…#…
…#…
…#…
#.@.##
.#…#.
【输出样例】
10
8
-1
思路
BFS算法。网上关于c++或是java的版本其实有很多,今天写一个python版本的AC代码。
maze=[] #创建迷宫
visited=[] #访问过的结点
dis=[]
nx = [[1, 0], [-1, 0], [0, -1], [0, 1]] #移动范围
n,m=map(int,input().split()) #输入行与列
for i in range(n):
temp = list(map(str, input()))
maze.append(temp)
dis = [[float('inf') for i in range(m)] for i in range(n)]
for temp in maze:
if "@" in temp:
start=(maze.index(temp),temp.index("@"))
if "*" in temp:
end = (maze.index(temp), temp.index("*"))
def bfs():
dis[start[0]][start[1]] = 0
q = []
node = (start[0],start[1])
q.append(node)
visited.append(node)
while len(q)>0:
point = q.pop(0)
if (point[0] == end[0] and point[1] == end[1]): #终点位置
break
for i in range(4): #下上左右
dx = point[0] + nx[i][0]
dy = point[1] + nx[i][1]
if (0 <= dx < n and 0 <= dy < m and maze[dx][dy] != "#" and (dx,dy) not in visited):
newPoint = (dx, dy)
visited.append(newPoint)
q.append(newPoint)
dis[dx][dy] = dis[point[0]][point[1]] + 1
if __name__ == '__main__':
bfs()
if dis[end[0]][end[1]] != float("inf"):
print(dis[end[0]][end[1]])
else:
print(-1)

浙公网安备 33010602011771号