我正在用Python实现广度优先搜索算法来解决8益智游戏http://mypuzzle.org/sliding。有人告诉我,这个算法运行时间不应超过几分钟,但它运行了一个多小时。我的算法或实现有问题吗?或者是那个告诉我这可能在几分钟内错误运行的人?
这是我的代码:
编辑:你可以在命令行中使用python driver.py bfs <nine numbers separated by commas>
运行它我正在使用python driver.py bfs 9,3,7,5,0,6,4,1,2
driver.py
import sys
from SearchAlgorithms import bfs#, dfs, ast, ida
if __name__=='__main__':
board = [int(s) for s in sys.argv[2].split(',')]
if(sys.argv[1]=='bfs'):
output = bfs(board)
elif(sys.argv[1]=='dfs'):
output = bfs(board)
elif(sys.argv[1]=='ast'):
output = bfs(board)
elif(sys.argv[1]=='ida'):
output = bfs(board)
else:
raise IOError
print(output)
SearchAlgorithms.py
from queue import Queue
import math
import time
import copy
class Board:
def __init__(self, data, path=[]):
self.data = data
self.path = path
def neighbors(self):
neighbors = []
board_width = int(math.sqrt(len(self.data)))
if self.data.index(0) - board_width >= 0:
new_data = copy.deepcopy(self.data)
new_data[self.data.index(0)], new_data[self.data.index(0) - board_width] = self.data[self.data.index(0) - board_width], 0
neighbors.append(Board(new_data, self.path + ['Up']))
if self.data.index(0) + board_width < len(self.data):
new_data = copy.deepcopy(self.data)
new_data[self.data.index(0)], new_data[self.data.index(0) + board_width] = self.data[self.data.index(0) + board_width], 0
neighbors.append(Board(new_data, self.path + ['Down']))
if self.data.index(0) - 1 >= 0:
new_data = copy.deepcopy(self.data)
new_data[self.data.index(0)], new_data[self.data.index(0) - 1] = self.data[self.data.index(0) - 1], 0
neighbors.append(Board(new_data, self.path + ['Left']))
if self.data.index(0) + 1 < len(self.data):
new_data = copy.deepcopy(self.data)
new_data[self.data.index(0)], new_data[self.data.index(0) + 1] = self.data[self.data.index(0) + 1], 0
neighbors.append(Board(new_data, self.path + ['Right']))
return neighbors
def bfs(board):
before = time.time()
goal = sorted(board)
graph = Board(board)
frontier = [graph]
explored = set()
count = 0
while frontier:
count +=1
if count % 100 == 0:
print(count)
state = frontier.pop(0)
explored.add(state)
if state.data == goal:
return {'path_to_goal': reversed(state.path),
'cost_of_path': len(state.path),
'nodes_expanded': len(explored),
'fringe_size': len(frontier),
'running_time': time.time() - before
}
for neighbor in state.neighbors():
if neighbor not in set().union(frontier, explored) :
frontier.append(neighbor)
return False
感谢您的帮助!