Python广度优先搜索实现八数码问题求解
本文介绍如何使用Python语言结合广度优先搜索(BFS)算法解决经典的八数码(九宫格)难题。通过定义状态类、生成子状态及路径回溯,实现从初始布局到目标布局的最少步数寻优,提供完整的代码逻辑与运行示例。
1.题目描述
八数码问题,亦称九宫格问题,是在一个3×3的棋盘上进行的。棋盘内放置了八个标有1至8数字的棋子,且每个棋子上的数字互不相同。棋盘上还留有一个空格,允许将与空格相邻的棋子移动至该空格位置。问题的核心目标是:给定一个初始状态和一个目标状态,寻找一种移动方案,使得从初始状态转换到目标状态所需的移动步数最少。
代码
使用算法:广度优先搜索算法
python
import numpy as np
class State:
def __init__(self, state, directionFlag=None, parent=None):
self.state = state
self.direction = ['up', 'down', 'right', 'left']
if directionFlag:
self.direction.remove(directionFlag)
self.parent = parent
self.symbol = ' '
def getDirection(self):
return self.direction
def showInfo(self):
for i in range(3):
for j in range(3):
print(self.state[i, j], end=' ')
print("\n")
print('->\n')
return
def getEmptyPos(self):
postion = np.where(self.state == self.symbol)
return postion
def generateSubStates(self):
if not self.direction:
return []
subStates = []
boarder = len(self.state) - 1
row, col = self.getEmptyPos()
if 'left' in self.direction and col > 0:
s = self.state.copy()
temp = s.copy()
s[row, col] = s[row, col-1]
s[row, col-1] = temp[row, col]
news = State(s, directionFlag='right', parent=self)
subStates.append(news)
if 'up' in self.direction and row > 0:
s = self.state.copy()
temp = s.copy()
s[row, col] = s[row-1, col]
s[row-1, col] = temp[row, col]
news = State(s, directionFlag='down', parent=self)
subStates.append(news)
if 'down' in self.direction and row < boarder:
s = self.state.copy()
temp = s.copy()
s[row, col] = s[row+1, col]
s[row+1, col] = temp[row, col]
news = State(s, directionFlag='up', parent=self)
subStates.append(news)
if self.direction.count('right') and col < boarder:
s = self.state.copy()
temp = s.copy()
s[row, col] = s[row, col+1]
s[row, col+1] = temp[row, col]
news = State(s, directionFlag='left', parent=self)
subStates.append(news)
return subStates
def solve(self):
openTable = []
closeTable = []
openTable.append(self)
steps = 1
while len(openTable) > 0:
n = openTable.pop(0)
closeTable.append(n)
subStates = n.generateSubStates()
path = []
for s in subStates:
if (s.state == s.answer).all():
while s.parent and s.parent != originState:
path.append(s.parent)
s = s.parent
path.reverse()
return path, steps+1
openTable.extend(subStates)
steps += 1
else:
return None, None
if __name__ == '__main__':
symbolOfEmpty = ' '
State.symbol = symbolOfEmpty
originState = State(np.array([[2, 8, 3], [1, 6 , 4], [7, symbolOfEmpty, 5]]))
State.answer = np.array([[1, 2, 3], [8, State.symbol, 4], [7, 6, 5]])
s1 = State(state=originState.state)
path, steps = s1.solve()
if path:
for node in path:
node.showInfo()
print(State.answer)
print("Total steps is %d" % steps)
以上就是Python利用广度优先搜索解决八数码难题的详细内容,更多关于Python实现广度搜索八数码的资料,敬请关注本站其他相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













