floyd 带路径记录

由于要做地图间的寻路,学习了下这个算法

记录下floyd 带路径算法(回路负权不适用)

在unity直接挂物体上运行即可

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

public class Floyd : MonoBehaviour
{
    List> adjacentMatrix;
    List> recordMatrix;
    int inf = 999999;
    void Start()
    {
        InitMatrix();
        floydCore();
        ShowPath(1, 5);
    }

    // Update is called once per frame
    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;

        List> recordMatrix = new List>{
            new List{0, 1, 2, 3, 4, 5},
            new List{0, 1, 2, 3, 4, 5},
            new List{0, 1, 2, 3, 4, 5},
            new List{0, 1, 2, 3, 4, 5},
            new List{0, 1, 2, 3, 4, 5},
            new List{0, 1, 2, 3, 4, 5},
        };
        this.recordMatrix = recordMatrix;
    }

    void floydCore()
    {
        int n = adjacentMatrix.Count;
        var e = adjacentMatrix;
        for (int k = 0; k < n; k++)
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    if (e[i][k] e[i][k] + e[k][j])
                    {
                        e[i][j] = e[i][k] + e[k][j];
                        recordMatrix[i][j] = recordMatrix[i][k];
                    }


        //根据邻接矩阵 输出最终的结果
        //for (int i = 0; i < n; i++)
        //{
        //   string str = "";
        //   for (int j = 0; j < n; j++)
        //   {
        //       str += e[i][j].ToString() + ", ";
        //   }
        //   Debug.Log(str+"\n");
        //}

        //输出记录路径
        for (int i = 0; i < n; i++)
        {
            string str = "";
            for (int j = 0; j < n; j++)
            {
                str += recordMatrix[i][j].ToString() + ", ";
            }
            Debug.Log(str + "\n");
        }
    }

    void ShowPath(int startIndex, int endIndex)
    {
        List path = new List();
        int st = startIndex;
        int end = endIndex;
        while (st != end)
        {
            path.Add(st);
            Debug.Log(st + "  "+end);
            int temp = recordMatrix[st][end];
            st = temp;

        }
        path.Add(end);

        for (int i = 0; i < path.Count; i++)
        {
            Debug.LogFormat("{0}->", path[i]);
        }
    }
}

 

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