Skip to content

Instantly share code, notes, and snippets.

@topnotch48
Created November 2, 2018 07:53
Show Gist options
  • Save topnotch48/17619d65f7353e1fee1adec94e01b8bc to your computer and use it in GitHub Desktop.
Save topnotch48/17619d65f7353e1fee1adec94e01b8bc to your computer and use it in GitHub Desktop.
public HashSet<T> BFS<T>(Graph<T> graph, T start) {
var visited = new HashSet<T>();
if (!graph.AdjacencyList.ContainsKey(start))
return visited;
var queue = new Queue<T>();
queue.Enqueue(start);
while (queue.Count > 0) {
var vertex = queue.Dequeue();
if (visited.Contains(vertex))
continue;
visited.Add(vertex);
foreach(var neighbor in graph.AdjacencyList[vertex])
if (!visited.Contains(neighbor))
queue.Enqueue(neighbor);
}
return visited;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment