首页 > 代码库 > 数据结构之图 Part3 – 2 遍历
数据结构之图 Part3 – 2 遍历
BFS
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace LH.GraphConsole{ class Program { private static bool[] visited; private static Queue<int> rootVertexQueue = new Queue<int>(); static void Main(string[] args) { BFSTranverse(); } private static void BFSTranverse() { 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]) { rootVertexQueue.Enqueue(i); while (rootVertexQueue.Count != 0) { var item = rootVertexQueue.Dequeue(); visited[i] = true; Console.WriteLine("visited vertex index: " + item); for (int j = 0; j < vertexNumber; j++) { if (graph.Edges[item, j] == 1 && !visited[j]) { rootVertexQueue.Enqueue(j); visited[j] = true; } } } } } } }}结果:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。