首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BFS的实现

BFS的实现
EN

Stack Overflow用户
提问于 2013-10-12 22:58:29
回答 1查看 452关注 0票数 0

我已经实现了广度优先搜索。邻接矩阵(Adj)表示不同节点之间的关系,节点存储在nodes[]中。

但是,我没有得到所需的遍历。请帮帮我。下面是我的代码。没有语法错误。这可能是一个逻辑错误,我无法通过调试来找出。

代码语言:javascript
复制
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;
         }
 }
 }
EN

回答 1

Stack Overflow用户

发布于 2014-10-03 12:49:40

试试这个..。它似乎对我很有效

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19335562

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档