【发布时间】:2021-02-26 04:00:11
【问题描述】:
我设计了一种算法,可以使用 BFS 或 DFS 解决 8 平方问题。当前的问题是它运行了无限长的时间。如果我让它运行 30 分钟左右。它以我的 RAM 得到结束完整。我的实现有什么问题。我无法成功调试此代码。 提前致谢。
import copy
import time
import pprint
def get_empty_board():
return [
[7,4,2],
[8,3,0],
[1,5,6]
]
end_state = [
[1,2,3],
[8,0,4],
[7,6,5]
]
def solve_squares(board):
states_explored = list()
states = [ (neighbor,[board] + [neighbor]) for neighbor in get_neighbors(board) ]
while states:
print(len(states))
current_state = states.pop(0)
if (current_state[0]) in states_explored:
continue
# if len(states) > 300:
# states =[ states[0] ]
# pprint.pprint(current_state)
# pprint.pprint(current_state)
if current_state[0] == end_state:
return True,current_state[1]
neighbors = get_neighbors(current_state[0])
states_explored.append(current_state[0])
for neighbor in neighbors:
if (neighbor) not in states_explored:
states.append((neighbor,current_state[1] + [neighbor]))
states_explored.append((neighbor[0]))
return False,None
def get_neighbors(board):
x = None
y = None
neighbors = list()
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
x = i
y = j
break
# print(x,y)
for i in range(len(board)):
for j in range(len(board[0])):
if abs(i-x) <= 1 and abs(j-y) <= 1:
if abs(i-x) != abs(j-y):
# print(i,j)
new_state = copy.deepcopy(board)
new_state[x][y] = new_state[i][j]
new_state[i][j] = 0
# pprint.pprint(new_state)
# time.sleep(5)
neighbors.append(new_state)
return neighbors
def main():
result,path = solve_squares(get_empty_board())
print(result)
print(path)
main()
【问题讨论】:
-
您收到了两个答案。你能留下一些反馈吗?
标签: python algorithm data-structures