单源最短路径Dijkstra算法 C#

原文为C++,用C#改写了一下。

http://www.dutor.net/index.php/2010/04/shortest-path-dijkstra/

ClassNode类

public class ClassNode
{
	public const int MAXINT = 0xFFFF;
	
	public ClassNode()
	{
		nodeLen = MAXINT;
		nodeAdd = false;
	}
	
	public int nodePre;
	public int nodeLen;
	public bool nodeAdd;
}

主程序

namespace DijkstraConsole
{
	class Program
	{
		public const int MAXINT = 0xFFFF;
		
		public static void Main(string[] args)
		{
			int n = 0;
			int node;
			int nline;
			int nfrom;
			int nto;
			int nlen;
			int nmin;
			int nstart;
			int nnext;
									
			Console.Write("请输入顶点数: ");
			node = int.Parse(Console.ReadLine());
			n = node;
			
			ClassNode[] classNode = new ClassNode[n];			
			int[,] Adj = new int[n,n];
			
			for (int i = 0; i < n; i ++)
			{
				for (int j = 0; j < n; j ++)
				{
					Adj[i,j] = MAXINT;
				}
				classNode[i] = new ClassNode();
				Adj[i,i] = 0;
			}
			
			Console.Write("请输入边数: ");
			nline = int.Parse(Console.ReadLine());
			Console.WriteLine();
			Console.WriteLine("=============基础数据输入=============");
			
			for (int i = 0; i < nline; i ++)
			{
				Console.Write("请输入起点: ");
				nfrom = int.Parse(Console.ReadLine());
				Console.Write("请输入终点: ");
				nto = int.Parse(Console.ReadLine());
				Console.Write("请输入距离: ");
				nlen = int.Parse(Console.ReadLine());
				
				Adj[ nfrom, nto ] = nlen;
				Console.WriteLine("起点:" + nfrom + "   " + "终点:" + nto + "   " + "距离:" + nlen);
			}
			
			Console.WriteLine("======================================");
			
			Console.Write("请输入源点: ");
			nstart = int.Parse(Console.ReadLine());
						
			classNode[nstart].nlen = 0;
			nnext = nstart;
			
			for (int i = 0; i < n; i ++)
			{
				nmin = MAXINT;
				int nodet = 0;				
				classNode[nnext].nodeAdd = true;
				
				for (int j = 0; j < n; j ++)
				{					
					if (classNode[j].nlen > classNode[nnext].nlen + Adj[nnext,j])
					{
						classNode[j].nlen = classNode[nnext].nlen + Adj[nnext,j];
						classNode[j].nodePre = nnext;
					}
					if (classNode[j].nlen < nmin && !classNode[j].nodeAdd)
					{
						nmin = classNode[j].nlen;
						nodet = j;
					}
				}				
				if (nmin == MAXINT) break;
				nnext = nodet;
			}
			
			for(int i = 0; i < n; i ++)
			{
				Console.WriteLine(classNode[i].nlen + "     " + classNode[i].nodeAdd);
			}				
			
			do
			{
				Console.Write("请输入目的地: ");
				nto = int.Parse(Console.ReadLine());
				
				int rp = nto;
				while(rp != nstart) // 反向输出路径
				{
					Console.Write(rp + " <- ");					
					rp = classNode[rp].nodePre;
				}
				Console.WriteLine(nstart);
				Console.WriteLine("Distance: " + classNode[nto].nlen);
			}
			while(nto < n);			
		}
	}
}
    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/lab2013/article/details/6843014
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞