单源最短路径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);			
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值