思路:单源顶点的最短路径扩散
using System;
using System.Collections.Generic;
using System.Text;
using static System.Console;
namespace DataStructure.graph
{
class Adjacency2//邻接矩阵初始化
{
public static int INFINTE = 99999;
public int[,] graph_matrix;
public Adjacency2(int[,] weigt_path,int number)//存入graph matrix
{
int i, j;
int start, end;
graph_matrix = new int[number, number];
for (i = 1; i < number; i++)
{
for (j = 1; j < number; j++)
{
if (i != j)
{
graph_matrix[i, j] = INFINTE;
}
else
{
graph_matrix[i, j] = 0;
}
}
}
for (i = 0; i < weigt_path.GetLength(0); i++)
{
start = weigt_path[i, 0];
end = weigt_path[i, 1];
graph_matrix[start, end] = weigt_path[i, 2];
}
}
public void print_table()//控制台打印
{
for(int i = 1; i < graph_matrix.GetLength(0); i++)
{
for(int j = 1; j < graph_matrix.GetLength(1); j++)
{
if(graph_matrix[i,j] == INFINTE)
{
Write(" x ");
}
else
{
if (graph_matrix[i, j] == 0) Write(" ");
Write(graph_matrix[i, j] + " ");
}
}
WriteLine();
}
}
}
class DijkstraAlgorithmSeekPath : Adjacency2
{
private int[] cost;
private int[] selected;
public DijkstraAlgorithmSeekPath(int[,] weigt_path, int number) : base(weigt_path, number)
{
cost = new int[number];
selected = new int[number];
for (int i=1;i<number;i++)//置为未选择
{
selected[i]=0;
}
}
public void shortestPath(int source)//计算最短路径
{
int shortest_distance;
int shortest_vertex = 1;
int i, j;
for (i = 1; i < graph_matrix.GetLength(0); i++)//源路径的可达点及距离记录下来
{
cost[i] = graph_matrix[source, i];
}
selected[source] = 1;
cost[source] = 0;
for (i=1;i<graph_matrix.GetLength(0)-1;i++)//计算到所有点的最短距离
{
shortest_distance = INFINTE;
for (j = 1; j < graph_matrix.GetLength(0); j++)//记录可达中最近的点
{
if(shortest_distance > cost[j] && selected[j] == 0)
{
shortest_vertex = j;
shortest_distance = cost[j];
}
}
selected[shortest_vertex] = 1;
for (j = 1; j < graph_matrix.GetLength(0); j++)//计算不可达点的最短距离
{
if (selected[j] == 0 &&
cost[shortest_vertex] + graph_matrix[shortest_vertex, j] < cost[j])
{
cost[j] = cost[shortest_vertex] + graph_matrix[shortest_vertex, j];
}
}
}
WriteLine("============================================");
WriteLine("顶点1到各顶点最短距离的结果");
WriteLine("============================================");
for (j = 1; j < graph_matrix.GetLength(0); j++)
{
WriteLine("顶点1到顶点" + j + "的最短距离= " + cost[j]);
}
}
public static void startDijkstra()
{
int[,] Weight_Path = { {1, 2, 10},{2, 3, 20},
{2, 4, 25},{3, 5, 18},
{4, 5, 22},{4, 6, 95},{5, 6, 77} };
DijkstraAlgorithmSeekPath obj = new DijkstraAlgorithmSeekPath(Weight_Path, 7);
WriteLine("==========================");
WriteLine("此范例图的邻接矩阵如下:");
WriteLine("==========================");
obj.print_table();
obj.shortestPath(1);
ReadKey();
}
}
}