深度优先用栈解决15数码问题并进行可视化_Python实现
时间: 2023-12-29 19:06:21 浏览: 60
好的,我可以为您提供Python代码来解决15数码问题并进行可视化。以下是代码:
```python
import copy
import time
# 定义初始状态
start_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
# 定义目标状态
goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
# 定义状态类
class State:
def __init__(self, state, parent, action, depth):
self.state = state
self.parent = parent
self.action = action
self.depth = depth
# 定义栈类
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def empty(self):
return len(self.stack) == 0
# 定义可视化函数
def visualize(state):
print("-------------")
for row in state:
print("|", end=" ")
for col in row:
if col == 0:
print(" ", end=" ")
else:
print(col, end=" ")
print("|", end=" ")
print()
print("-------------")
# 定义移动函数
def move(state, direction):
new_state = copy.deepcopy(state)
for i in range(len(new_state)):
for j in range(len(new_state[i])):
if new_state[i][j] == 0:
if direction == "up" and i > 0:
new_state[i][j], new_state[i - 1][j] = new_state[i - 1][j], new_state[i][j]
return new_state
elif direction == "down" and i < len(new_state) - 1:
new_state[i][j], new_state[i + 1][j] = new_state[i + 1][j], new_state[i][j]
return new_state
elif direction == "left" and j > 0:
new_state[i][j], new_state[i][j - 1] = new_state[i][j - 1], new_state[i][j]
return new_state
elif direction == "right" and j < len(new_state[i]) - 1:
new_state[i][j], new_state[i][j + 1] = new_state[i][j + 1], new_state[i][j]
return new_state
return None
# 定义判断函数
def is_goal(state):
return state.state == goal_state
# 定义搜索函数
def dfs(start):
stack = Stack()
visited = set()
stack.push(start)
while not stack.empty():
cur = stack.pop()
visualize(cur.state)
if is_goal(cur):
return cur
visited.add(str(cur.state))
for direction in ["up", "down", "left", "right"]:
new_state = move(cur.state, direction)
if new_state is not None and str(new_state) not in visited:
child = State(new_state, cur, direction, cur.depth + 1)
stack.push(child)
return None
# 主函数
def main():
start = State(start_state, None, None, 0)
start_time = time.time()
result = dfs(start)
end_time = time.time()
if result is None:
print("No solution found")
else:
print("Solution found in {} seconds".format(end_time - start_time))
print("Total moves: ", result.depth)
if __name__ == '__main__':
main()
```
代码中首先定义了初始状态和目标状态。接着定义了状态类和栈类。可视化函数用来展示当前状态。移动函数用来移动空格。判断函数用来判断当前状态是否为目标状态。搜索函数使用深度优先搜索算法,搜索过程中将状态压入栈中,并将已访问的状态记录在visited集合中,防止重复访问。主函数调用搜索函数,并计算搜索所用的时间。
阅读全文