Please comment on my DFS implementation and test, I would like to get comments about algorithm correctness.
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace JobInterviewTests
{
[TestClass]
public class DFSUnitTest
{
[TestMethod]
public void CheckCorrectOrder()
{
GraphNode root = new GraphNode("A");
root.Neighbors.Add(new GraphNode("F"));
root.Neighbors.Add(new GraphNode("E"));
var temp = new GraphNode("B");
var temp2 = new GraphNode("C");
var temp3 = new GraphNode("D");
temp2.Neighbors.Add(temp3);
temp.Neighbors.Add(temp2);
root.Neighbors.Add(temp);
List<string> result =TraverseDFS(root);
Assert.AreEqual("A",result[0]);
Assert.AreEqual("B",result[1]);
Assert.AreEqual("C",result[2]);
Assert.AreEqual("D",result[3]);
Assert.AreEqual("E",result[4]);
Assert.AreEqual("F",result[5]);
}
private List<string> TraverseDFS(GraphNode root)
{
if (root == null)
{
return null;
}
List<string> result = new List<string>();
Stack<GraphNode> s = new Stack<GraphNode>();
s.Push(root);
while (s.Any())
{
GraphNode curr = s.Pop();
result.Add(curr.Value);
foreach (var node in curr.Neighbors)
{
s.Push(node);
}
}
return result;
}
}
public class GraphNode
{
public string Value { get; set; }
public List<GraphNode> Neighbors { get; set; }
public GraphNode(string s)
{
Value = s;
Neighbors = new List<GraphNode>();
}
}
}