DFS
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LH.GraphConsole { class Program { private static bool[] visited; static void Main(string[] args) { DFSTranverse(); } private static void DFSTranverse() { int vertexNumber = 9; int edgeNumber = 15; Graph graph = new Graph(vertexNumber, edgeNumber); graph.Vertexs[0] = "A"; graph.Vertexs[1] = "B"; graph.Vertexs[2] = "C"; graph.Vertexs[3] = "D"; graph.Vertexs[4] = "E"; graph.Vertexs[5] = "F"; graph.Vertexs[6] = "G"; graph.Vertexs[7] = "H"; graph.Vertexs[8] = "I"; graph.Edges[0, 1] = 1; graph.Edges[0, 5] = 1; graph.Edges[1, 2] = 1; graph.Edges[1, 8] = 1; graph.Edges[1, 6] = 1; graph.Edges[2, 3] = 1; graph.Edges[2, 8] = 1; graph.Edges[3, 8] = 1; graph.Edges[3, 6] = 1; graph.Edges[3, 7] = 1; graph.Edges[3, 4] = 1; graph.Edges[4, 7] = 1; graph.Edges[4, 5] = 1; graph.Edges[5, 6] = 1; graph.Edges[6, 7] = 1; visited = new bool[vertexNumber]; for (int i = 0; i < vertexNumber; i++) { if (!visited[i]) { DFS(graph, i); } } } private static void DFS(Graph graph, int vertexIndex) { visited[vertexIndex] = true; Console.WriteLine("Visit vertex index: " + vertexIndex); var size = graph.Vertexs.Count(); for (int i = 0; i < size; i++) { if (graph.Edges[vertexIndex, i] == 1 && !visited[i]) { DFS(graph, i); } } } } } 输出结果: