public void TriangularGrid() { var g = new TestGraph(Enumerable.Range(1, 10).ToArray()) { { 1, new[] { 2, 3 } }, { 2, new[] { 3, 4, 5 } }, { 3, new[] { 5, 6 } }, { 4, new[] { 5, 7, 8 } }, { 5, new[] { 6, 8, 9 } }, { 6, new[] { 9, 10 } }, { 7, new[] { 8 } }, { 8, new[] { 9 } }, { 9, new[] { 10 } }, { 10 }, }; var spGraph = ShortestPathGraph.Build(g, edge => edge.Owner == -1, new[] { 1 }); spGraph.ShouldBeEquivalentTo( new TestShortestPathGraph { { 1, 0, new[] { 2, 3 } }, { 2, 1, new[] { 4, 5 } }, { 3, 1, new[] { 5, 6 }, new[] { 2 } }, { 4, 2, new[] { 7, 8 } }, { 5, 2, new[] { 8, 9 }, new[] { 4 } }, { 6, 2, new[] { 9, 10 }, new[] { 5 } }, { 7, 3 }, { 8, 3, null, new[] { 7 } }, { 9, 3, null, new[] { 8 } }, { 10, 3, null, new[] { 9 } }, }); }
public void Simple() { var g = new TestGraph(1, 2, 3, 4) { { 1, new[] { 2, 3 } }, { 2, new[] { 3, 4 } }, { 3, new[] { 4 } }, { 4 } }; var spGraph = ShortestPathGraph.Build(g, edge => edge.Owner == -1, new[] { 1 }); spGraph.ShouldBeEquivalentTo( new TestShortestPathGraph { { 1, 0, new[] { 2, 3 } }, { 2, 1, new[] { 4 } }, { 3, 1, new[] { 4 }, new[] { 2 } }, { 4, 2 } }); }
public static ShortestPathGraph Build(Graph graph, Func <Edge, bool> takeEdge, ICollection <int> sourceVertexes) { var spGraph = new ShortestPathGraph(); var queue = new Queue <ShortestPathVertex>(); foreach (var sourceVertex in sourceVertexes) { queue.Enqueue(spGraph.AddVertex(sourceVertex, 0)); } while (queue.Any()) { var from = queue.Dequeue(); foreach (var edge in graph.Vertexes[from.Id].Edges) { if (!takeEdge(edge)) { continue; } if (spGraph.Vertexes.ContainsKey(edge.To)) { var to = spGraph.Vertexes[edge.To]; if (to.Distance == from.Distance + 1) { spGraph.AddEdge(edge); } else if (to.Distance == from.Distance && from.Id < to.Id) { spGraph.AddSameLayerEdge(edge); } continue; } spGraph.AddEdge(edge); queue.Enqueue(spGraph.AddVertex(edge.To, from.Distance + 1)); } } return(spGraph); }