0

我已经实现了广度优先搜索。邻接矩阵(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;
         }
 }
 }
4

1 回答 1

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
于 2014-10-03T04:49:40.413 回答