zoukankan      html  css  js  c++  java
  • 广度优先算法解决无向无权图的最短路径问题

    从城市1到城市到城市5有很多条路,现在需要找出从1到3的最短路径。

    无向图:意思是来回的路径值是一样的

    无权图:意思是每条路径的值是一样的

    package myalgorithm;
    import java.util.LinkedList;
    import java.util.Queue;
    /*BFS用于记录的位置和值的结构*/
    class node
    {
        node(int cur,int valparam)
        {
            this.cur = cur;
            this.value = valparam;
        }
        int cur,value;
    }
    public class ShortPath {
        /*路是对称的,-1表示此路不通*/
        int[][] graph = {
                { 0, 1, 1,-1,-1},
                { 1, 0, 1, 1,-1},
                { 1, 1, 0, 1, 1},
                {-1, 1, 1, 0, 1},
                {-1, 1, 1,-1, 0}
           
        };
        /*全局最短路径*/
        public int stepnum = 999;
        /*初始标记数组都为0*/
        public int[]mark = new int[graph.length];
    
      /*BFS算法*/
        public void BFS(node startPoint)
        {
            //起始点装入队列
            Queue<node> queue = new LinkedList<node>();
            queue.offer(startPoint);
            
            node t1;
            top:
            while(!queue.isEmpty())
            {
                //取队首,出队后不再入队,value也自此固定
                t1 = queue.poll();
                mark[t1.cur] = t1.value;//标记步数
                for(int i=0;i<5;i++)
                {
                    //找到目的地5
                    if(i==4 && graph[t1.cur][i] != -1)
                    {
                        stepnum = t1.value + 1;//下一步可到
                        mark[t1.cur] = stepnum;
                        break top;
                    }
                    //继续接着找,把空路径添加到队列末尾
                    //路是通的,并且没有被标记
                    if(graph[t1.cur][i] != -1 
                            &&mark[i] == 0)
                    {
                        //入队
                        queue.offer(new node(i,t1.value+1));
                    }
                }
            }
        }
       
        /*main函数*/
        public static void main(String[] args) {
            ShortPath my = new ShortPath();
            long start = System.currentTimeMillis();
            my.BFS(new node(0,0));
            long end = System.currentTimeMillis();
            System.out.println("BFS step: " + my.stepnum + " time:" + (end-start));      
        }
    
    }
  • 相关阅读:
    php多态
    ssl certificate problem: self signed certificate in certificate chain
    test plugin
    open specific port on ubuntu
    junit vs testng
    jersey rest service
    toast master
    use curl to test java webservice
    update folder access
    elk
  • 原文地址:https://www.cnblogs.com/mingziday/p/4851853.html
Copyright © 2011-2022 走看看