public IEnumerator <BfsVertice <T> > GetEnumerator() { var visited = new HashSet <T>(); var queue = new Queue <BfsVertice <T> >(); // NOTE: questionable usage of default(T) - it is not meaningful for non-reference types, especially for integers queue.Enqueue(new BfsVertice <T>(_source, default(T), 0)); while (queue.Count > 0) { var bfsVertice = queue.Dequeue(); if (!visited.Contains(bfsVertice.Vertice)) { visited.Add(bfsVertice.Vertice); foreach (var adjacentVertice in _graph.GetAdjacentVertices(bfsVertice.Vertice)) { queue.Enqueue(new BfsVertice <T>(adjacentVertice, bfsVertice.Vertice, bfsVertice.Distance + 1)); } } yield return(bfsVertice); } }
public IEnumerator <DfsVertice <T> > GetEnumerator() { var visited = new Dictionary <T, VerticeColor>(); var stack = new Stack <DfsVertice <T> >(); var timestamp = 0; var source = new DfsVertice <T>(_source, default(T)); source.DiscoveredTimestamp = timestamp++; stack.Push(source); while (stack.Count > 0) { var vertice = stack.Pop(); var color = VerticeColor.White; visited.TryGetValue(vertice.Vertice, out color); switch (color) { case VerticeColor.White: visited[vertice.Vertice] = VerticeColor.Gray; vertice.DiscoveredTimestamp = timestamp++; stack.Push(vertice); foreach (var adjacentVertice in _graph.GetAdjacentVertices(vertice.Vertice)) { var adjacentColor = VerticeColor.White; visited.TryGetValue(adjacentVertice, out adjacentColor); if (adjacentColor == VerticeColor.White) { stack.Push(new DfsVertice <T>(adjacentVertice, vertice.Vertice)); } } break; case VerticeColor.Gray: visited[vertice.Vertice] = VerticeColor.Black; stack.Push(vertice); break; case VerticeColor.Black: vertice.TraversedTimestamp = timestamp++; yield return(vertice); break; } } }