python - Implementing Depth Limited Path Finding with Stack -
hey title says i'm trying implement depth limited search in python3 returns path given graph, start vertex , goal vertex. i'm struggling bit how enforce limit search. far have:
def dfs(g, v, goal, limit=-1): sentinel = object() visitedstack = [v] path = "" while visitedstack: currentvertex = visitedstack.pop() if g.getvertex(currentvertex) != none: if g.getvertex(currentvertex).visited == false: path += currentvertex + ' -> ' g.getvertex(currentvertex).hasbeenvisited() if currentvertex == goal: return path[:-3] elif currentvertex == sentinel: limit += 1 elif limit != 0: limit -= 1 visitedstack.append(sentinel) visitedstack.extend(g.getvertex(currentvertex).getconnections()) return "depth limit reached"
edit: changed of code check visited vertices. after edit search getting returned doesn't work sometimes. example, i'll set depth limit 3, have path of 4 or 5 getting returned. other times i'll set limit 7 , have "limit reached" returned. note: smallest path 3
when search goes deeper level, push sentinel onto stack , decrement limit. when pop sentinel off stack increment level.
def dfs_limit(g, start, goal, limit=-1): ''' perform depth first search of graph g. if limit >= 0, maximum depth of search. ''' sentinel = object() visitedstack = [start] path = [] while visitedstack: currentvertex = visitedstack.pop() if currentvertex == goal: path.append(currentvertex) return ' -> '.join(path) elif currentvertex == sentinel: #finished level; go 1 level limit += 1 path.pop() elif limit != 0: # go 1 level deeper, push sentinel limit -= 1 path.append(currentvertex) visitedstack.append(sentinel) visitedstack.extend(g.getvertex(currentvertex).getconnections())
if there loops or multiple routes through graph, need keep track of nodes have been visited don't duplicate work or in endless loop.
Comments
Post a Comment