我最近开始尝试编写一个程序,该程序使用 Zelle 的 python 编程书中的 graphics.py 模块。该程序的想法是创建一个图形窗口并接受两个点,开始和结束。它绘制起点并进行 bfs 搜索,然后一旦到达终点,它就会绘制最短路径(反正还没有对角线)。它在技术上是有效的,但它非常慢,并且在前两到三个迭代之后的任何地方都需要很长时间。而且我尝试到处寻找具有快速查找的数据结构,以及实现节点以允许回溯的有效方法,但我就是想不通。在向我解释我可以做些什么来改进我的实施时,我将不胜感激。
这是python 3.5.2中的代码:
from graphics import *
from collections import deque
TITLE = "Breadth-First Search"
WIDTH = 500
HEIGHT = 500
win = GraphWin(TITLE, WIDTH, HEIGHT)
win.setCoords(0,0,20,20)
class Node:
def __init__(self, x, y, parent = None):
self.x = x
self.y = y
self.parent = parent
self.pos2D = Point(self.x, self.y)
self.pos2D.draw(win)
def getPos(self):
return (self.x, self.y)
def draw(self, win, color = None):
if color != None:
self.pos2D.undraw()
self.pos2D.setFill(color)
self.pos2D.draw(win)
return
self.pos2D.draw(win)
def neighbors(state):
return (Node(state.x, state.y+1, state), Node(state.x, state.y-1,
state), Node(state.x-1, state.y, state), Node(state.x+1, state.y,
state))
def drawPath(endState):
state.draw(win, 'red')
while state.parent != None:
state = state.parent
state.draw(win, 'red')
def bfs():
start = (10,10)
finish = (15,15)
explored = set()
frontier = deque()
frontier.append((Node(start[0], start[1])))
while len(frontier) != 0:
state = frontier.popleft()
explored.add(state)
if state.getPos() == finish:
break
for neighbor in neighbors(state):
if neighbor not in explored:
frontier.append(neighbor)
bfs()