问问下面这个哪里有问题呀?
python代码
import queue
def swap(index1, index2, string) -> str:
if not((0 <= index1 / 3 < 3 and 0 <= index1 % 3 < 3) and (0 <= index2 / 3 < 3 and 0 <= index2 % 3 < 3)):
return string
char_list = list(string)
char_list[index1], char_list[index2] = char_list[index2], char_list[index1]
return ''.join(char_list)
def bfs(start):
# initiate the distance and queue
q = queue.Queue()
q.put(start)
dis[start] = 0
# while queue not empty
while not q.empty():
# get the top element
mid_state = q.get()
# print(' '.join(mid_state[:3]))
# print(' '.join(mid_state[3:6]))
# print(' '.join(mid_state[6:]))
# print(mid_state)
index_x = mid_state.find("x")
# print("index_x = ",index_x)
distance = dis[mid_state]
# print(distance)
# print and end
if mid_state == "12345678x":
print(distance)
break
# loop the 4 directions and change the state
for i in range(4):
'''
1 2 3
x 4 6
7 5 8
'''
if i == 0:
# up swap the mid_state[index_x - 3] and mid_state[index_x]
swap_state = swap(index_x - 3, index_x, mid_state)
if i == 1:
# right
swap_state = swap(index_x + 1, index_x, mid_state)
if i == 2:
# down
swap_state = swap(index_x + 3, index_x, mid_state)
if i == 3:
swap_state = swap(index_x - 1, index_x, mid_state)
# update the dis and put in the queue
# print("swap: ", swap_state)
if swap_state not in dis:
dis[swap_state] = distance + 1
q.put(swap_state)
if __name__ == "__main__":
dis = {}
# ['1', '2',...]
start_list = input().split(" ")
start = ''.join(start_list)
bfs(start)