/// <summary> /// Privat helper. Breadth First Search from Single Source. /// </summary> private void _breadthFirstSearch(IGraph <T> graph, T source) { // Define helper variables. var current = source; var queue = new DataStructures.Lists.Queue <T>(_verticesCount); // Set distance to current to zero _distances[_nodesToIndices[current]] = 0; // Set current to visited: true. _visited[_nodesToIndices[current]] = true; queue.Enqueue(current); while (!queue.IsEmpty) { current = queue.Dequeue(); int indexOfCurrent = _nodesToIndices[current]; foreach (var adjacent in graph.Neighbours(current)) { int indexOfAdjacent = _nodesToIndices[adjacent]; if (!_visited[indexOfAdjacent]) { _predecessors[indexOfAdjacent] = indexOfCurrent; _distances[indexOfAdjacent] = _distances[indexOfCurrent] + 1; _visited[indexOfAdjacent] = true; queue.Enqueue(adjacent); } } //end-foreach } //end-while }
/// <summary> /// A breadth first search traversal of the graph, starting from a specified vertex. /// Returns the visited vertices of the graph. /// </summary> public virtual IEnumerable <T> BreadthFirstWalk(T source) { // Check for existence of source if (VerticesCount == 0) { return(new ArrayList <T>(0)); } else if (!HasVertex(source)) { throw new KeyNotFoundException("The source vertex doesn't exist."); } var visited = new HashSet <T>(); var queue = new DataStructures.Lists.Queue <T>(); var listOfNodes = new ArrayList <T>(VerticesCount); listOfNodes.Add(source); visited.Add(source); queue.Enqueue(source); while (!queue.IsEmpty) { var current = queue.Dequeue(); var neighbors = Neighbours(current); foreach (var adjacent in neighbors) { if (!visited.Contains(adjacent)) { listOfNodes.Add(adjacent); visited.Add(adjacent); queue.Enqueue(adjacent); } } } return(listOfNodes); }
/// <summary> /// Privat helper. Breadth First Search from Multiple Sources. /// </summary> private void _breadthFirstSearch(IGraph <T> graph, IList <T> sources) { // Define helper variables. var queue = new DataStructures.Lists.Queue <T>(_verticesCount); foreach (var source in sources) { if (!graph.HasVertex(source)) { throw new Exception("Graph doesn't has a vertex '" + source + "'"); } int index = _nodesToIndices[source]; _distances[index] = 0; _visited[index] = true; queue.Enqueue(source); } while (!queue.IsEmpty) { var current = queue.Dequeue(); int indexOfCurrent = _nodesToIndices[current]; foreach (var adjacent in graph.Neighbours(current)) { int indexOfAdjacent = _nodesToIndices[adjacent]; if (!_visited[indexOfAdjacent]) { _predecessors[indexOfAdjacent] = indexOfCurrent; _distances[indexOfAdjacent] = _distances[indexOfCurrent] + 1; _visited[indexOfAdjacent] = true; queue.Enqueue(adjacent); } } //end-foreach } //end-while }