首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >图算法的C++实现

图算法的C++实现
EN

Stack Overflow用户
提问于 2011-10-22 23:48:57
回答 1查看 2K关注 0票数 1

我正在尝试实现宽度优先搜索算法,以便找到两个顶点之间的最短距离。我开发了一个队列对象来保存和检索对象,并且我有一个二维数组来保存两个给定顶点之间的边的长度。我试图填充一个二维数组,以保持两个顶点之间的最短距离。

然而,我遇到的问题是,无论我请求的是两个顶点的最短距离,都返回0。这是我算法的实现;如果你能让我走上正确的轨道,帮助我解决我的问题,那就太棒了。

代码语言:javascript
复制
 for (int i = 0; i < number_of_vertex; i++) 
 //For every vertex, so that we may fill   the array
 {
  int[] dist = new int[number_of_vertex]; 
  //Initialize a new array to hold the values for the distances

for (int j = 0; x < number_of_vertex; j++)
{
    dist[j] = -1; 
   //All distance values will be set to -1 by default; this will be changed later on
 }

  dist[i] = 0; //The source node's distance is set to 0 (Pseudocode line 4)

   myQueue.add(i); //Add the source node's number to the queue (Pseudocode line 3)

   while (!myQueue.empty()) //Pseudocode line 5
   {
      int u = myQueue.eject(); //Pseudocode line 6

      for (int y = 0; y < number_of_vertex; y++) //Pseudocode line 7
      {
          if (edge_distance(u,y) > 0)
          {
              if (dist[y] == -1)
              {
                  myQueue.add(y);
                  dist[y] = dist[u] + 1;
                  shortest_distance[i][u] = dist[y];
               }
           }    
        }                 
     }  
}
EN

回答 1

Stack Overflow用户

发布于 2011-10-23 00:58:09

好的..。我想问题是关于使用的算法和使用的术语。

“为了找到两个顶点之间的最短距离”,你的意思是连通图中两个顶点之间的最短路径?

您要编写的算法是Dijkstra的算法(这是名称)。

http://www.cs.berkeley.edu/~vazirani/algorithms/chap4.pdf

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7863388

复制
相关文章

相似问题

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