zoukankan      html  css  js  c++  java
  • 求有向图中两点间所有路径

    public class GraphPath {
    //有向带权图。-1表示无路可通。自己到自己也是-1。其它表示权值。
        private static int[][] graph=
        {
            {-1,2,3,3},//表示 0点到0点不连通;0点到1点连通,权值2;0点到2点连通,权值3,0点到3点连通,权值3
            {-1,-1,-1,2},
            {-1,2,-1,3},
            {-1,-1,-1,-1}       
        };
        private static boolean[] hasFlag=new boolean[graph.length];
        //true-表示该结点已访问过。false-表示还没有访问过。
         
        private static ArrayList res=new ArrayList();
        //最后的所有的路径的结果。每一条路径的格式是如:0->2->1->3:7
         
        //求在图graph上源点s到目标点d之间所有的简单路径,并求出路径的和。   
        public static void getPaths(int s,int d,String path,int sum)
        {
            hasFlag[s]=true;//源点已访问过. 
         for(int i=0;i
         {
            if (graph[s][i]==-1 || hasFlag[i]){continue;}
            //若无路可通或已访问过,则找下一个结点。
     
            if(i==d)//若已找到一条路径
           
                res.add(path+"->"+d+":"+(sum+graph[s][i]));//加入结果。
                continue;
            }
            getPaths(i, d, path+"->"+i, sum+graph[s][i]);//继续找
            hasFlag[i]=false;       
         }//for(i)
        }
          
        public static void main(String[] args) {
            // TODO Auto-generated method stub
          getPaths(0, 3, ""+0, 0);//从源点:0 到目点:3,初始路径:"0" 初始和:0
          for(String e:res)//打印所有的结果
          {
              System.out.println(e);
          }
        }
    }

  • 相关阅读:
    常见数据结构图文详解-C++版
    求单链表中环的起点,原理详解
    Qt Creator 整合 python 解释器教程
    Qt 共享库(动态链接库)和静态链接库的创建及调用
    qt creator 中的"提升为..."功能简介
    QT 操作 excel 教程
    网易2017校园招聘算法题c语言实现源码
    c语言版贪吃蛇小游戏
    mysql语法结构
    Spring MVC rest接收json中文格式数据显示乱码
  • 原文地址:https://www.cnblogs.com/luckForever/p/7254237.html
Copyright © 2011-2022 走看看