Dijkstra算法(带路径记录)

计算起点到各个节点的最短路径,并记录路径节点

根据图得到邻接矩阵(下图的邻接表)

Dijkstra算法(带路径记录)_第1张图片

unity里面挂到物体运行即可看到结果 

using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

public class Dijkstra : MonoBehaviour
{
    int inf = 999999;
    List> adjacentMatrix;
    List dis = new List(); //起始点1距离其他节点的距离
    List book = new List(); //记录遍历过的节点
    int VertexCount = 6; //节点个数
    int[] recoderPath = new int[6] { 0,0,0,0,0,0};  //记录路径节点
    void Start()
    {
        InitMatrix();
        dijkstra();
        StringBuilder str = new StringBuilder();
        StringBuilder str2 = new StringBuilder();
        for (int i = 0; i < dis.Count; i++)
        {
            str.Append(dis[i].ToString()).Append(",");
            str2 .Append(recoderPath[i].ToString()).Append(",");
        }
        Debug.Log(str.ToString());
        Debug.Log(str2.ToString());
        ShowPath(1, 4);
    }

    void InitMatrix()
    {
        List> matrix = new List>{
            new List{0, 1, 11, inf, inf, inf },
            new List{inf, 0, 8, 3, inf, inf },
            new List{inf, inf, 0, inf, 5, inf },
            new List{inf, inf, 4, 0, 13, 16 },
            new List{inf, inf, inf, inf, 0, 4},
            new List{inf, inf, inf, inf, inf, 0 },
        };
        adjacentMatrix = matrix;
        for (int i = 0; i < VertexCount; i++)
        {
            //Debug.Log(i);
            dis.Add(adjacentMatrix[0][i]) ;
            book.Add(0);
            recoderPath[i] = 0; //0为起始节点
            
        }
        book[0] = 1; //起点记作已经遍历过的
    }

    void dijkstra()
    {
        //Dijkstra算法核心语句
        int n = VertexCount;
        var e = adjacentMatrix;
        for (int i = 0; i < n-1; i++)
        {
            //找到离起始节点(1节点)最近的 节点
            int min = inf;
            int next = 0;
            for (int j = 0; j < n; j++)
            {
                if (book[j] == 0 && dis[j] < min)
                {
                    min = dis[j];
                    next = j;
                }
            }
            book[next] = 1;
            
            for (int k = 0; k < n; k++)
            {
                if (e[next][k] < inf && dis[k] > dis[next] + e[next][k])
                {
                    dis[k] = dis[next] + e[next][k];
                    recoderPath[k] = next;
                }
            }
        }
    }

    //倒序输出路径点(不包含起点和终点)
    void ShowPath(int startIndex, int endIndex)
    {
        endIndex = recoderPath[endIndex];       
        if (startIndex != endIndex)
        {
            Debug.LogFormat("{0}", endIndex);
            ShowPath(startIndex, endIndex);
        }
    }
}

 

你可能感兴趣的:(算法)