6th National Championship java test question 4: crossing the minefield

Through the minefield


X-Star’s tank chariot is very strange. It must alternately pass through the positive energy radiation area and the negative energy radiation area to maintain normal operation, otherwise it will be scrapped. A certain tank needs to go from zone A to zone B (zones A and B are safe zones and have no positive or negative energy characteristics). How can the path be the shortest?
The known map is a square matrix, with letters marking areas A and B, and other areas are marked with positive or negative signs to indicate positive and negative energy radiation areas.
E.g:

A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
坦克车只能水平或垂直方向上移动到相邻的区。
数据格式要求:
输入第一行是一个整数n,表示方阵的大小, 4<=n<100
接下来是n行,每行有n个数据,可能是A,B,+,-中的某一个,中间用空格分开。A,B都只出现一次。
要求输出一个整数,表示坦克从A区到B区的最少移动步数。
如果没有方案,则输出-1
例如:
用户输入:
5
A + - + -
- + - - +
- + + + -
+ - + - +
B + - + -
则程序应该输出:
10

Idea:
This problem is very similar to the maze problem, but the addition of the queue is different. We first find the starting point A and then add it to the queue. In reverse, I use f=[[1,0],[-1,0],[0,1],[0,-1]] to indicate
Yes , we add to the queue. Conditions: The upper level is + when it is +, this time it will go -; the
upper level is-when it is this time, it will go +;
it's a bit like a moving wall, and then you can keep searching for the nearest Step counted.
program:

n=int(input())
m=[input().replace(" ","") for i in range(n)]
c=[[-1 for i1 in range(n)] for i in range(n)]
d=[]
f=[[1,0],[-1,0],[0,1],[0,-1]]
def bfs():
    while  d!=[]:
        x,y=d.pop(0)
        
        for i in f:
            x1=x+i[0]
            y1=y+i[1]
            if -1<x1<n and -1<y1<n and c[x1][y1]==-1:
                if m[x1][y1]=="B":
                    c[x1][y1]=c[x][y]+1
                    return c[x1][y1]
                if (m[x][y]=="-" and m[x1][y1]=="+" )or (m[x][y]=="+" and m[x1][y1]=="-") or m[x][y]=="A":
                    d.append([x1,y1])
                    c[x1][y1]=c[x][y]+1

for i in range(n):
    for j in range(n):
        if m[i][j]=="A":
            d.append([i,j])
            c[i][j]=0
            break
print(bfs())

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112861892