最小生成树和最短路径的区别

最小生成树能够保证整个拓扑图的所有路径之和最小,但不能保证任意两点之间是最短路径。

最短路径是从一点出发,到达目的地的路径最小。

最小生成树所有点被连通  。把连通的图的所有顶点连起来路径之和最小的问题,即生成树总权值之和最小。整体来分析。

最短路径不一定所有点。只着眼于点与点之间的路径问题,并不关注整个图,也就意味着对一个节点运行算法的结果与另一个节点的结果之间没有多少关系。单条路径来分析。

Prims算法代码

while(alreadyVisited.size() != Switches.size())
            {
                Vector neighbors = getNeighborSet(topo, Switches, alreadyVisited);
                Vector CostOfNeighbors = new Vector();
                int cost = 40000000;
                ASwitch srcsw = null, dstsw = null;
                for(int i = 0;i < neighbors.size();i++)
                {
                    ASwitch sw1 = (ASwitch)neighbors.get(i);
                    for(int j = 0;j < alreadyVisited.size();j++)
                    {
                        ASwitch sw2 = (ASwitch)alreadyVisited.get(j);
                        int tempcost = getCost(topo, sw1, sw2, insid, "legacy");
                        if( (tempcost > 0) && (tempcost < cost ))
                        {
                            cost = tempcost;
                            srcsw = sw1;
                            dstsw = sw2;
                        }
                    }
                }//end for neighbors
                //得到一个最小花费的邻居
                alreadyVisited.add(srcsw);
                
                treenode temptr = new treenode();
                temptr.Mac = srcsw.SWName;
                current.childlist.push(temptr);
                current = temptr;
            }//end while

dijkstra算法

while(Visited.size() != Switches.size())
              {
                  for(int i = 0;i < alreadyVisited.size(); i ++)
                  {
                      ASwitch sw1 = (ASwitch)alreadyVisited.get(i);
                      System.out.println("already visited: "+sw1.SWName);
                      Vector ng = getNeighbors(topo, Switches, sw1);
                      alreadyVisited.remove(sw1);
                      //Visited.add(sw1);
                      Visited = addtoVector(Visited,sw1);
                      for(int j = 0;j < ng.size();j++)
                      {
                          ASwitch sw2 = (ASwitch)ng.get(j);
                          if((swValue.get(sw2) == 0) ) continue;
                          int tempcost = -1;
                          int tcost = getCost(topo, sw1, sw2, insid, "legacy");;
                          if(tcost >0 ) tempcost = swValue.get(sw1)+tcost;
                          if((tempcost > 0) && (tempcost < swValue.get(sw2)))
                          {
                              swValue.put(sw2, tempcost);
                              presw.put(sw2, sw1);
                              System.out.println("sw: "+sw2.SWName+"   cost: "+tempcost+"   presw: "+sw1.SWName);
                              
                              alreadyVisited.add(sw2);
         
                          }
                      }
                  }
              }

上一篇:华为eNSP—三层交换实验


下一篇:单臂路由简单基础配置