Tips

 


Dijstra algorithm can help you to find all shortest path from start node to all other nodes.

 

Core logic

calculate the shortest path from start node to all adjacent node.

Get the shortest connected node from the left over set

re-calculate the distance from current node to other nodes by considering start to current, if find smaller one, replace distance and parent vertex.

        public void Path()
        {
            // validation
            if (this.GraphSize == 0)
            {
                return;
            }

            // init
            this.Verticies[0].inTree = true;
            nTree++;

            for (int i = 0; i < this.GraphSize; i++)
            {
                this.sPath[i].parentNode = 0;
                this.sPath[i].distance = this.AdjMatrix[0, i];
            }

            while (nTree <= this.GraphSize)
            {
                // get the current not in tree and minimal node
                int indexMin = GetMin(); //从剩下的集合中找到距离从顶点到其距离最短的点。
                int startToCurrent = this.sPath[indexMin].distance; // 拿到顶点到当前点的距离
                this.Verticies[indexMin].inTree = true; // 放到集合中
                nTree++;//  very important!!, otherwise, dead loop
                // update the distance from start via current node to other nodes
                AdjustShortPath(indexMin, startToCurrent);// 如果发现更短的距离,调整其他节点的parent node和距离
            }

            // reset
            for(int i = 0; i < this.GraphSize; i++)
            {
                this.Verticies[i].inTree = false;
            }

            nTree = 0;
        }

 

Code

using System;
using System.Collections.Generic;
using System.Linq;

namespace TestCase1.TestCase.WeightedGraph1
{
    public class Vertex<T>
    {
        public T Data
        {
            get;
            set;
        }

        public bool inTree
        {
            get;
            set;
        }

        public Vertex(T data)
        {
            this.Data = data;
        }
    }

    public class DistTracking
    {
        public int parentNode
        {
            get;
            set;
        }

        public int distance
        {
            get;
            set;
        }

        public DistTracking(int parentNode, int distance)
        {
            this.parentNode = parentNode;
            this.distance = distance;
        }
    }

    public class WeightedGraph1<T>
    {
        public int[,] AdjMatrix
        {
            get;
            set;
        }

        private int GraphSize = 0;
        private int nTree = 0;

        private List<Vertex<T>> Verticies = null;

        private int infinity = int.MaxValue / 10;

        private DistTracking[] sPath = null;

        public WeightedGraph1(int capacity)
        {
            this.Verticies = new List<Vertex<T>>();
            this.AdjMatrix = new int[capacity, capacity];
            this.sPath = new DistTracking[capacity];

            // init all matrix
            for (int i = 0; i < capacity; i++)
            {
                for (int j = 0; j < capacity; j++)
                {
                    this.AdjMatrix[i, j] = infinity;
                }
            }

            // init sPath<---------------!!!  pay attention to this, make sure all member variables are initialized
            for (int i = 0; i < capacity; i++)
            {
                this.sPath[i] = new DistTracking(0, infinity);
            }
        }

        public void AddVertex(T data)
        {
            var ret = this.Verticies.Where(t => t.Data.Equals(data));
            if (ret == null || ret.Any()) // !  if has result, return;  make sure if condition is corect
            {
                return;
            }

            this.Verticies.Add(new Vertex<T>(data));
            this.GraphSize++;
        }

        public void AddDirectedEdge(int from, int to, int weight)
        {
            this.AdjMatrix[from, to] = weight;
        }

        public void Path()
        {
            // validation
            if (this.GraphSize == 0)
            {
                return;
            }

            // init
            this.Verticies[0].inTree = true;
            nTree++;

            for (int i = 0; i < this.GraphSize; i++)
            {
                this.sPath[i].parentNode = 0;
                this.sPath[i].distance = this.AdjMatrix[0, i];
            }

            while (nTree <= this.GraphSize)
            {
                // get the current not in tree and minimal node
                int indexMin = GetMin();
                int startToCurrent = this.sPath[indexMin].distance;
                this.Verticies[indexMin].inTree = true;
                nTree++;//  very important!!, otherwise, dead loop
                // update the distance from start via current node to other nodes
                AdjustShortPath(indexMin, startToCurrent);
            }

            // reset
            for(int i = 0; i < this.GraphSize; i++)
            {
                this.Verticies[i].inTree = false;
            }

            nTree = 0;
        }

        public void PrintPath()
        {
            for(int i = 0; i < this.GraphSize; i++)
            {
                Console.Write("FOR Node {0} , via parent {1}, the shortest path from 0 to it is {2}", this.Verticies[i].Data, this.sPath[i].parentNode, this.sPath[i].distance);
                Console.WriteLine();
            }
        }

        private void AdjustShortPath(int currentVertex, int startToCurrent)
        {
            for (int column = 1; column < this.GraphSize; column++)
            {
                if (this.Verticies[column].inTree)
                {
                    continue;
                }
                else
                {
                    int startToFringe = startToCurrent + this.AdjMatrix[currentVertex, column];
                    if (startToFringe < this.sPath[column].distance)// here is column as index, not currentVer as index
                    {
                        this.sPath[column].distance = startToFringe;
                        this.sPath[column].parentNode = currentVertex;
                    }
                }
            }
        }

        private int GetMin()
        {
            int minDex = 0;
            int minDist = infinity;

            for (int j = 0; j < this.GraphSize; j++)
            {
                if (this.Verticies[j].inTree == false && this.sPath[j].distance < minDist)
                {
                    minDex = j;
                    minDist = sPath[j].distance;
                }
            }

            return minDex;
        }
    }
}

 


 

posted on 2018-03-15 14:04  xuyanran  阅读(130)  评论(0编辑  收藏  举报