我实施了广度优先搜索。邻接矩阵(adj [] [])表示不同节点之间的关系,节点存储在节点[]中。
但是,我没有得到所需的遍历。请帮帮我。以下是我的代码。没有语法错误。这可能是一个逻辑错误,我无法通过调试找到。
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;
}
}
}
答案 0 :(得分:0)
试试这个..它似乎对我有用
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 None