/// <summary> /// Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. /// Finds all vertices that can be reached by the starting vertex. /// </summary> /// <param name="rootVertex"></param> /// <returns></returns> public Dictionary <T, BfsVertexInfo <T> > BreadthFirstSearch(T rootVertex, Action <T> preVisit = null) { // Traversed graph information var visitedVerticesInfo = new Dictionary <T, BfsVertexInfo <T> >(); if (!_aList.ContainsKey(rootVertex)) { return(visitedVerticesInfo); } // Initialize it foreach (var i in _aList) { visitedVerticesInfo[i.Key] = new BfsVertexInfo <T>(); } // Set the distance for the root vertex visitedVerticesInfo[rootVertex] = new BfsVertexInfo <T>() { Distance = 0 }; // Create a queue and add root vertex QueueLinkedList <T> queue = new QueueLinkedList <T>(); queue.Enqueue(rootVertex); // As long as the queue is not empty: while (!queue.IsEmpty()) { // Repeatedly dequeue a vertex u from the queue. var vertex = queue.Dequeue(); Console.Write(vertex + " "); // Trace the path preVisit?.Invoke(vertex); // For each neighbor v of u that has not been visited: foreach (var neighbor in _aList[vertex]) { if (visitedVerticesInfo[neighbor].Distance == null) { // Set distance to 1 greater than u's distance visitedVerticesInfo[neighbor].Distance = visitedVerticesInfo[vertex].Distance + 1; // Set predecessor to u visitedVerticesInfo[neighbor].Predecessor = vertex; // Enqueue v queue.Enqueue(neighbor); } } } return(visitedVerticesInfo); }
/// <summary> /// TODO: Add a description what is going on here /// </summary> /// <param name="graph"></param> /// <param name="source"></param> /// <returns></returns> public static BfsVertexInfo <int?>[] DoBfs(int[][] graph, int source) { BfsVertexInfo <int?>[] bfsInfo = new BfsVertexInfo <int?> [graph.Length]; // Initialize bfsInfo array for (int i = 0; i < graph.Length; i++) { bfsInfo[i] = new BfsVertexInfo <int?> { Distance = null, Predecessor = null }; } bfsInfo[source].Distance = 0; var queue = new QueueLinkedList <int>(); queue.Enqueue(source); while (!queue.IsEmpty()) { var u = queue.Dequeue(); for (int i = 0; i < graph[u].Length; i++) { var v = graph[u][i]; if (bfsInfo[v].Distance == null) { bfsInfo[v].Distance = bfsInfo[u].Distance + 1; bfsInfo[v].Predecessor = u; queue.Enqueue(v); } } } return(bfsInfo); }