Skip to content

Instantly share code, notes, and snippets.

@scalvert
Forked from riyadparvez/DFS.cs
Last active August 29, 2015 14:04
Show Gist options
  • Save scalvert/5da1bc8fcb8d10a535c7 to your computer and use it in GitHub Desktop.
Save scalvert/5da1bc8fcb8d10a535c7 to your computer and use it in GitHub Desktop.
public class Tree<K, V>
where K : class, IComparable<K>
where V : class
{
private Node<K, V> root;
public V DepthFirstSearch(K key)
{
Stack<Node<K, V>> stack = new Stack<Node<K, V>>();
root.Visited = true;
stack.Push(root);
while(stack.Any())
{
var node = stack.Pop();
if (node.Key == key)
{
return node.Value;
}
foreach (var child in node.GetAdjacentUnvisitedNodes())
{
child.Visited = true;
stack.Push(child);
}
}
return default(V);
}
private class Node<K, V>
where K : class, IComparable<K>
where V : class
{
public K Key { get; set; }
public V Value { get; set; }
public bool Visited { get; set; }
public IList<Node<K, V>> Nodes { get; set; }
public IList<Node<K, V>> GetAdjacentUnvisitedNodes()
{
return this.Nodes.Where(n => !n.Visited);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment