作者Luos (Soul)
看板Python
标题depth and breadth first search 问题
时间Thu Feb 26 05:25:36 2009
各位大大好....
python学习历经2个月 受到各位大力帮忙 实在非常感谢~~~
如今再次遇到危机了>"<
我必须要用breadth first search 或 depth first search 来找 path
breadth first search 只有办法回传 hop的数量 但没办法回传path
以下是我的breadth first search 得程式..
def bfs(self, top_node, bottom_node):
visited = []
visited_parent = []
hop = 0
queue = deque([top_node])
while queue:
curr_node = queue.popleft()
if curr_node in visited:
continue
if curr_node == bottom_node:
print "found path from " + top_node.node_num + " to " +
bottom_node.node_num + " with visited "
self.hop_matrix[int(top_node.node_num)].append(hop)
break
visited.append(curr_node)
if len(queue) == 0 or curr_node == queue[0]:
hop = hop + 1
queue.extend(curr_node.neighber_list)
但是不管怎麽试都没办法回传path...
感谢wikipedia提供的范例~
depth first search 回传path时会连我不想要的node都加进去.....
以下是我的depth first search
def dfs(node, target, path):
if node.value == target.value:
return path
else:
path.append(node)
for neighber in node.neighber_list:
if not neighber in path:
temp_path = dfs(neighber, target, path)
当找到时回传的path会盖掉原本的path...
这问题一直修不好...
坦白说吧 这两个都写的很不好=.=
想请教一下各位大大有没有比较好的写法~~
感谢各位大力帮忙XD
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 128.223.178.4
1F:推 liangjr:path是mutable所以会被改掉 02/26 10:05
2F:→ Luos:今天去找老师...结果他用最直接的方法..在queue直接放一个pat 03/03 02:56
3F:→ Luos:th list 进去 03/03 02:57
4F:→ qrtt1:那就是资料结构课本写的方法了啊 ha ha 03/03 21:17