我目前正在尝试使用 Python 编写一个简单的多线程程序。但是我遇到了一个我认为我错过的错误。我正在尝试简单地编写一个使用蛮力方法解决以下问题的程序:
从图像中可以看出,有一个棋盘,骑士在各个方格中移动。
我的方法是简单地尝试每一种可能的方式,其中每一种可能的方式都是一个新线程。如果在线程结束时没有可能的移动,如果等于 63,则计算访问了多少个正方形,在简单文本文件上写入解决方案...
代码如下:
from thread import start_new_thread
import sys
i=1
coor_x = raw_input("Please enter x[0-7]: ")
coor_y = raw_input("Please enter y[0-7]: ")
coordinate = int(coor_x), int(coor_y)
def checker(coordinates, previous_moves):
possible_moves = [(coordinates[0]+1, coordinates[1]+2), (coordinates[0]+1, coordinates[1]-2),
(coordinates[0]-1, coordinates[1]+2), (coordinates[0]-1, coordinates[1]-2),
(coordinates[0]+2, coordinates[1]+1), (coordinates[0]+2, coordinates[1]-1),
(coordinates[0]-2, coordinates[1]+1), (coordinates[0]-2, coordinates[1]-1)]
to_be_removed = []
for index in possible_moves:
(index_x, index_y) = index
if index_x < 0 or index_x > 7 or index_y < 0 or index_y > 7:
to_be_removed.append(index)
for index in previous_moves:
if index in possible_moves:
to_be_removed.append(index)
if not to_be_removed:
for index in to_be_removed:
possible_moves.remove(index)
if len(possible_moves) == 0:
if not end_checker(previous_moves):
print "This solution is not correct"
else:
return possible_moves
def end_checker(previous_moves):
if len(previous_moves) == 63:
writer = open("knightstour.txt", "w")
writer.write(previous_moves)
writer.close()
return True
else:
return False
def runner(previous_moves, coordinates, i):
if not end_checker(previous_moves):
process_que = checker(coordinates, previous_moves)
for processing in process_que:
previous_moves.append(processing)
i = i+1
print "Thread number:"+str(i)
start_new_thread(runner, (previous_moves, processing, i))
else:
sys.exit()
previous_move = []
previous_move.append(coordinate)
runner(previous_move, coordinate, i)
c = raw_input("Type something to exit !")
我愿意接受所有建议...我的示例输出如下:
Please enter x[0-7]: 4
Please enter y[0-7]: 0
Thread number:2
Thread number:3
Thread number:4
Thread number:5Thread number:4
Thread number:5
Thread number:6Thread number:3Thread number:6Thread number:5Thread number:6
Thread number:7
Thread number:6Thread number:8
Thread number:7
Thread number:8Thread number:7
Thread number:8
Thread number:4
Thread number:5
Thread number:6Thread number:9Thread number:7Thread number:9
Thread number:10
Thread number:11
Thread number:7
Thread number:8
Thread number:9
Thread number:10
Thread number:11
Thread number:12
Thread number:5Thread number:5
Thread number:6
Thread number:7
Thread number:8
Thread number:9
Thread number:6
Thread number:7
Thread number:8
Thread number:9
如果似乎由于某种原因线程数停留在 12...任何帮助将是最受欢迎的...
谢谢