两点间的所有路径
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphAllRoad { class Program { static int node = 7;//节点数 static Stack<int> singleRoad = new Stack<int>();//保存单条路径 static int[,] matrix;//邻接矩阵 static bool[] visited = new bool[node];//节点访问与否 static int intNum = 0; static void Main(string[] args) { Console.WriteLine("****初始化邻接矩阵****"); Init(); Console.WriteLine("*****矩阵初始化成功*****"); Console.WriteLine("&&&&&&&&&&&&&&&&&&&"); Console.WriteLine("****节点编号初始化****"); for (int i = 0; i < node; i++) { Console.Write((i + 1).ToString() + " "); } Console.WriteLine(); Console.WriteLine("*****编号初始化成功*****"); Console.WriteLine("&&&&&&&&&&&&&&&&&&&"); Console.WriteLine("&&&&&&&&&&&&&&&&&&&"); Console.WriteLine("请输入路径起点:"); int startPoint =Convert.ToInt32(Console.ReadLine()); Console.WriteLine("请输入路径终点:"); int endPoint = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("&&&&&&&&&&&&&&&&&&&"); Console.WriteLine("&&&&&&&&&&&&&&&&&&&"); Console.WriteLine("****深度搜索算法寻找{0}-{1}间的所有路径****", startPoint, endPoint); Console.WriteLine("结果输出如下:"); DFS(matrix, startPoint-1, endPoint-1); Console.WriteLine("共{0}条路径",intNum); Console.ReadLine(); } /// <summary> /// 初始化邻接矩阵 /// </summary> static void Init() { matrix = new int[,] { { 0, 1, 0, 1, 0, 0, 0 }, { 1, 0, 1, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0, 1, 0 }, {1,1,1,0,1,0,0 },{0,0,0,1,0,1,1 },{0,0,1,0,1,0,1 },{0,0,0,0,1,1,0 } }; for (int i = 0; i < node; i++) { for (int j = 0; j < node; j++) { Console.Write(matrix[i, j] + " "); } Console.WriteLine(); } } /// <summary> /// 路径输出 /// </summary> static void Output() { for (int i = singleRoad.Count - 1; i > 0; i--) { Console.Write("{0}→", singleRoad.ElementAt<int>(i) + 1); } Console.Write("{0}", singleRoad.ElementAt<int>(0) + 1); Console.WriteLine(); } /// <summary> /// 深度搜索遍历算法 /// </summary> /// <param name="_matrix">邻接矩阵</param> /// <param name="startPoint">路径起始点</param> /// <param name="endPoint">路径终止点</param> static void DFS(int[,] _matrix, int startPoint, int endPoint) { singleRoad.Push(startPoint);//将当前节点入栈 visited[startPoint] = true;//将该节点标记为已经访问过 int midIndex = 0;//用于寻找下一个节点的索引 while (singleRoad.Count != 0)//栈中有元素 { //如果当前节点就是目标节点 if (startPoint == endPoint) { Output();//输出路径 intNum++; singleRoad.Pop();//退栈 回溯 visited[startPoint] = false;//将其设置为没有被访问过 break;//退出递归 } //如果没有到节点endPoint while (midIndex < node) { if (_matrix[startPoint, midIndex] == 1 && visited[midIndex] == false) { DFS(_matrix, midIndex, endPoint);//递归查询 } midIndex++; } //找到最后一个节点 if (midIndex == node) { visited[singleRoad.ElementAt<int>(0)] = false;//先标记栈中最后一个元素没有被访问过 singleRoad.Pop();//退栈 回溯 break;//退出一个递归 } } } } }