X星的坦克战车很奇怪,它必须交替地穿越正能量辐射区和负能量辐射区才能保持正常运转,否则将报废。
某坦克需要从A区到B区去(A,B区本身是安全区,没有正能量或负能量特征),怎样走才能路径最短?
已知的地图是一个方阵,上面用字母标出了A,B区,其它区都标了正号或负号分别表示正负能量辐射区。
例如:
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
坦克车只能水平或垂直方向上移动到相邻的区。
数据格式要求:
输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。
A,B都只出现一次。
要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1
例如:
用户输入:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
则程序应该输出:
10
from queue import Queue
n = int(input())
la = []
dir = [[-1, 0], [1, 0], [0, -1], [0, 1]]
vis = [[0] * n for i in range(n)]
def right(x, y):
if x >= 0 and x < n and y >= 0 and y < n:
return True
for i in range(n):
l = list(map(str, input().split()))
la.append(l)
for i in range(n):
for j in range(n):
if la[i][j] == "A":
a, b = i, j
if la[i][j] == "B":
x1, y1 = i, j
step=0
def bfs(x, y):
global step
q = Queue()
q.put((x, y, 0))
vis[x][y] = 1
while q.empty() == False:
now = q.get()
step=now[2]
if now[0] == x1 and now[1] == y1:
return step
for i in range(4):
nx = now[0] + dir[i][0]
ny = now[1] + dir[i][1]
if right(nx, ny) and vis[nx][ny] == 0 and la[now[0]][now[1]] != la[nx][ny]:
q.put((nx, ny, step + 1))
vis[nx][ny] = 1
return -1
print(bfs(a,b))