/// <summary> /// Swap two values in an ArrayList<T> collection given their indexes. /// </summary> public static void Swap <T>(this ArrayListGeneric <T> list, int firstIndex, int secondIndex) { if (list.Count < 2 || firstIndex == secondIndex) //This check is not required but Partition function may make many calls so its for perf reason { return; } var temp = list[firstIndex]; list[firstIndex] = list[secondIndex]; list[secondIndex] = temp; }
/// <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 ArrayListGeneric <T>(0)); } else if (!HasVertex(source)) { throw new KeyNotFoundException("The source vertex doesn't exist."); } var visited = new HashSet <T>(); var queue = new QueueGeneric <T>(); var listOfNodes = new ArrayListGeneric <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> /// A depth first search traversal of the graph, starting from a specified vertex. /// Returns the visited vertices of the graph. /// </summary> public virtual IEnumerable <T> DepthFirstWalk(T source) { // Check for existence of source if (VerticesCount == 0) { return(new ArrayListGeneric <T>(0)); } else if (!HasVertex(source)) { throw new KeyNotFoundException("The source vertex doesn't exist."); } var visited = new HashSet <T>(); var stack = new StackGeneric <T>(); var listOfNodes = new ArrayListGeneric <T>(VerticesCount); stack.Push(source); while (!stack.IsEmpty) { var current = stack.Pop(); if (!visited.Contains(current)) { listOfNodes.Add(current); visited.Add(current); foreach (var adjacent in Neighbours(current)) { if (!visited.Contains(adjacent)) { stack.Push(adjacent); } } } } return(listOfNodes); }