我已经实现了广度优先搜索。邻接矩阵(Adj)表示不同节点之间的关系,节点存储在nodes[]中。
但是,我没有得到所需的遍历。请帮帮我。下面是我的代码。没有语法错误。这可能是一个逻辑错误,我无法通过调试来找出。
insert(nodes[0]);
nos = nos + 1;
visited[nos] = nodes[0];
while(front != -1)
{
char ch = remove();
for(int i=0;i<n;i++)
{
if(ch == nodes[i])
{
pos = i;
}
}
for(int j=0;j<n;j++)
{
if(adj[j][pos] == 1)
{
for(int k=0;k<=nos;k++)
{
if(visited[k] == nodes[j])
{
goto end;
}
}
nos = nos + 1;
visited[nos] = nodes[j];
insert(nodes[j]);
end:continue;
}
}
}发布于 2014-10-03 12:49:40
试试这个..。它似乎对我很有效
def bfs(graph, start, goal):
if start == goal:
return None
frontier = [start]
explored = []
num_explored = 0
while len(frontier) > 0:
node = frontier.pop(0)
explored.append(node)
for edge in networkx.edges(graph, node):
child = State(graph, node)
if (child not in explored) and (child not in frontier):
if child == goal:
print "Path found in BFS"
return child
else:
frontier.append(child)
num_explored = num_explored + 1
print "BFS path failed"
return Nonehttps://stackoverflow.com/questions/19335562
复制相似问题