public void UndirectedPathToFiveHasOneVertices() { var input = CreateTestInput(); var g = new Graph(GraphType.Undirected, input, 7); var search = new Bfs(g, 0); Assert.AreEqual(1, search.DistanceTo(5)); }
public void UndirectedPathToFiveHasTwoVertices() { var input = CreateTestInput(); var g = new Graph(GraphType.Undirected, input, 7); var search = new Dfs(g, 0); var path = search.PathTo(5).ToArray(); Assert.AreEqual(2, search.DistanceTo(5)); Assert.AreEqual(2, path[0]); Assert.AreEqual(5, path[1]); }
public void UndirectedConnectionsAreMarked() { var input = CreateTestInput(); var g = new Graph(GraphType.Undirected, input, 7); var search = new Dfs(g, 0); Assert.IsTrue(search.Marked(2)); Assert.IsTrue(search.Marked(3)); Assert.IsTrue(search.Marked(5)); Assert.IsFalse(search.Marked(1)); Assert.IsFalse(search.Marked(4)); Assert.IsFalse(search.Marked(6)); }
public Bfs(Graph graph, int root) { if (graph == null) { throw new ArgumentNullException("graph"); } this.marked = new bool[graph.Vertices()]; this.edgeTo = Enumerable.Repeat(-1, graph.Vertices()).ToArray(); this.distTo = Enumerable.Repeat(-1, graph.Vertices()).ToArray(); this.count = 0; this.root = root; this.BreadthFirstSearch(graph, root); }
public void UndirectedHasPathToAreCorrect() { var input = CreateTestInput(); var g = new Graph(GraphType.Undirected, input, 7); var search = new Dfs(g, 0); Assert.IsTrue(search.HasPathTo(2)); Assert.IsTrue(search.HasPathTo(3)); Assert.IsTrue(search.HasPathTo(5)); Assert.IsFalse(search.HasPathTo(0)); // No path to self Assert.IsFalse(search.HasPathTo(1)); Assert.IsFalse(search.HasPathTo(4)); Assert.IsFalse(search.HasPathTo(6)); }
public void UndirectedCreateIsCorrectlyBuilt() { var input = CreateTestInput(); var g = new Graph(GraphType.Undirected, input, 7); Assert.AreEqual(7, g.Vertices()); Assert.AreEqual(10, g.Edges()); Assert.AreEqual(3, g.Adjacent(0).Count); Assert.AreEqual(1, g.Adjacent(1).Count); Assert.AreEqual(2, g.Adjacent(2).Count); Assert.AreEqual(1, g.Adjacent(3).Count); Assert.AreEqual(0, g.Adjacent(4).Count); Assert.AreEqual(2, g.Adjacent(5).Count); Assert.AreEqual(1, g.Adjacent(6).Count); }
public void BreadthFirstSearch(Graph graph, int root) { var vertices = new Queue<int>(); vertices.Enqueue(root); distTo[root] = 0; marked[root] = true; count++; while (vertices.Count > 0) { var currentVertice = vertices.Dequeue(); foreach (var vert in graph.Adjacent(currentVertice)) { if (!marked[vert]) { edgeTo[vert] = currentVertice; distTo[vert] = distTo[currentVertice] + 1; marked[vert] = true; count++; vertices.Enqueue(vert); } } } }