floyd 带路径记录

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

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

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

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

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

    // Update is called once per frame
    void InitMatrix()
    {
        List<List<int>> matrix = new List<List<int>>{
            new List<int>{0, 1, 11, inf, inf, inf },
            new List<int>{inf, 0, 8, 3, inf, inf },
            new List<int>{inf, inf, 0, inf, 5, inf },
            new List<int>{inf, inf, 4, 0, 13, 16 },
            new List<int>{inf, inf, inf, inf, 0, 4},
            new List<int>{inf, inf, inf, inf, inf, 0 },
        };
        adjacentMatrix = matrix;

        List<List<int>> recordMatrix = new List<List<int>>{
            new List<int>{0, 1, 2, 3, 4, 5},
            new List<int>{0, 1, 2, 3, 4, 5},
            new List<int>{0, 1, 2, 3, 4, 5},
            new List<int>{0, 1, 2, 3, 4, 5},
            new List<int>{0, 1, 2, 3, 4, 5},
            new List<int>{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]<inf && e[k][j] < inf && e[i][j] > 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<int> path = new List<int>();
        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]);
        }
    }
}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读