public void FindShortestPathForSimpleUndirectedGraphUsingDijkstraAlgorithm() { var graph = new UndirectedGraph<object, Edge<object>>(true); object v1 = "vertex1"; object v2 = "vertex2"; object v3 = "vertex3"; var e1 = new Edge<object>(v1, v2); var e2 = new Edge<object>(v2, v3); var e3 = new Edge<object>(v3, v1); graph.AddVertex(v1); graph.AddVertex(v2); graph.AddVertex(v3); graph.AddEdge(e1); graph.AddEdge(e2); graph.AddEdge(e3); var algorithm = new UndirectedDijkstraShortestPathAlgorithm<object, Edge<object>>(graph, edge => (double)1); var observer = new UndirectedVertexPredecessorRecorderObserver<object, Edge<object>>(); using (observer.Attach(algorithm)) { algorithm.Compute(v1); } IEnumerable<Edge<object>> path; observer.TryGetPath(v3, out path); foreach (var edge in path) { Console.WriteLine(edge); } }
static void Main(string[] args) { UndirectedGraph<int, Edge<int>> graph = new UndirectedGraph<int, Edge<int>>(true); // Add vertices to the graph graph.AddVertex(0); graph.AddVertex(1); graph.AddVertex(2); graph.AddVertex(3); graph.AddVertex(4); graph.AddVertex(5); // Create the edges Edge<int> e0_1 = new Edge<int>(0, 1); Edge<int> e0_2 = new Edge<int>(0, 2); Edge<int> e1_2 = new Edge<int>(1, 2); Edge<int> e3_4 = new Edge<int>(3, 4); Edge<int> e4_5 = new Edge<int>(4, 5); Edge<int> e3_5 = new Edge<int>(3, 5); // Add the edges graph.AddEdge(e0_1); graph.AddEdge(e0_2); graph.AddEdge(e1_2); graph.AddEdge(e3_4); graph.AddEdge(e4_5); graph.AddEdge(e3_5); List<int> path = new List<int>(); HamiltonianDefiner definer = new HamiltonianDefiner(graph); bool isHamiltonian = definer.isHamiltonianGraph(path); Console.WriteLine(isHamiltonian); Console.ReadLine(); }
public void test3() { UndirectedGraph<int, Edge<int>> graph = new UndirectedGraph<int, Edge<int>>(true); // Add vertices to the graph graph.AddVertex(0); graph.AddVertex(1); graph.AddVertex(2); graph.AddVertex(3); graph.AddVertex(4); // Create the edges Edge<int> e0_1 = new Edge<int>(0, 1); Edge<int> e0_2 = new Edge<int>(0, 2); Edge<int> e1_4 = new Edge<int>(1, 4); Edge<int> e3_4 = new Edge<int>(3, 4); Edge<int> e0_3 = new Edge<int>(0, 3); Edge<int> e1_2 = new Edge<int>(1, 2); // Add the edges graph.AddEdge(e0_1); graph.AddEdge(e0_2); graph.AddEdge(e1_2); graph.AddEdge(e1_4); graph.AddEdge(e3_4); graph.AddEdge(e0_3); List<int> path = new List<int>(); HamiltonianDefiner definer = new HamiltonianDefiner(graph); bool isHamiltonian = definer.isHamiltonianGraph(path); Assert.AreEqual(isHamiltonian, true); }
private UndirectedGraph<int, UndirectedEdge<int>> constructGraph(Tuple<int, int>[] vertices) { var g = new UndirectedGraph<int, UndirectedEdge<int>>(); foreach (var pair in vertices) { g.AddVerticesAndEdge(new UndirectedEdge<int>(pair.Item1, pair.Item2)); } return g; }
private UndirectedGraph<int, TaggedUndirectedEdge<int, double>> createGraph(List<TaggedUndirectedEdge<int, double>> edges) { var g = new UndirectedGraph<int, TaggedUndirectedEdge<int, double>>(true); foreach (TaggedUndirectedEdge<int, double> edge in edges) { g.AddVerticesAndEdge(edge); } return g; }
// effects: Given a list of cells, segments them into multiple // "groups" such that view generation (including validation) of one // group can be done independently of another group. Returns the // groups as a list (uses the foreign key information as well) internal List<CellGroup> GroupRelatedCells() { // If two cells share the same C or S, we place them in the same group // For each cell, determine the Cis and Sis that it refers // to. For every Ci (Si), keep track of the cells that Ci is // contained in. At the end, run through the Cis and Sis and do a // "connected components" algorithm to determine partitions var extentGraph = new UndirectedGraph<EntitySetBase>(EqualityComparer<EntitySetBase>.Default); var extentToCell = new Dictionary<EntitySetBase, Set<Cell>>(EqualityComparer<EntitySetBase>.Default); foreach (var cell in m_cells) { foreach (var extent in new[] { cell.CQuery.Extent, cell.SQuery.Extent }) { Set<Cell> cellsWithExtent; if (!extentToCell.TryGetValue(extent, out cellsWithExtent)) { extentToCell[extent] = cellsWithExtent = new Set<Cell>(); } cellsWithExtent.Add(cell); extentGraph.AddVertex(extent); } extentGraph.AddEdge(cell.CQuery.Extent, cell.SQuery.Extent); var associationSetExtent = cell.CQuery.Extent as AssociationSet; if (associationSetExtent != null) { foreach (var end in associationSetExtent.AssociationSetEnds) { extentGraph.AddEdge(end.EntitySet, associationSetExtent); } } } foreach (var fk in m_foreignKeyConstraints) { extentGraph.AddEdge(fk.ChildTable, fk.ParentTable); } var groupMap = extentGraph.GenerateConnectedComponents(); var result = new List<CellGroup>(); foreach (var setNum in groupMap.Keys) { var cellSets = groupMap.ListForKey(setNum).Select(e => extentToCell[e]); var component = new CellGroup(); foreach (var cellSet in cellSets) { component.AddRange(cellSet); } result.Add(component); } return result; }
public static Pixel GetOrAddVertex(int x, int y, UndirectedGraph<Pixel, TaggedUndirectedEdge<Pixel, EdgeTag>> graph) { Pixel p = VertexSearch(x, y, graph); if (p == null) { p = new Pixel(x, y, Color.Blue); graph.AddVertex(p); } return p; }
public void AddEdge_Test() { var ug = new UndirectedGraph(10); ug.AddEdge(4, 0); ug.AddEdge(4, 3); ug.AddEdge(4, 7); Assert.AreEqual(3, ug.E); }
public static IEnumerable<UndirectedGraph<string, Edge<string>>> GetUndirectedGraphs() { yield return new UndirectedGraph<string, Edge<string>>(); foreach (var g in GetAdjacencyGraphs()) { var ug = new UndirectedGraph<string, Edge<string>>(); ug.AddVerticesAndEdgeRange(g.Edges); yield return ug; } }
public void RemoveEdgeThrowsKeyNotFoundException79() { UndirectedGraph<int, Edge<int>> undirectedGraph; Edge<int> edge; bool b; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; edge = EdgeFactory.Create(0, 0); b = this.RemoveEdge<int, Edge<int>>(undirectedGraph, edge); }
public static UndirectedGraph<int, SEdge<int>> Create(bool allowParallelEdges) { UndirectedGraph<int, SEdge<int>> undirectedGraph = new UndirectedGraph<int, SEdge<int>>(allowParallelEdges); return undirectedGraph; // TODO: Edit factory method of UndirectedGraph`2<Int32,SEdge`1<Int32>> // This method should be able to configure the object in all possible ways. // Add as many parameters as needed, // and assign their values to each field by using the API. }
private UndirectedGraph<int, UndirectedEdge<int>> BuildGraph(int[] verticies, int[] edges) { var graph = new UndirectedGraph<int, UndirectedEdge<int>>(); graph.AddVertexRange(verticies); var convEdges = new UndirectedEdge<int>[edges.Length / 2]; for (int i = 0; i < edges.Length; i += 2) { convEdges[i / 2] = new UndirectedEdge<int>(edges[i], edges[i + 1]); } graph.AddEdgeRange(convEdges); return graph; }
private int CalcBicliqueCount(int[] verticies, int[] edges) { var g = new UndirectedGraph<int, IEdge<int>>(); g.AddVertexRange(verticies); var convEdges = new Edge<int>[edges.Length / 2]; for (int i = 0; i < edges.Length; i += 2) { convEdges[i / 2] = new Edge<int>(edges[i], edges[i + 1]); } g.AddEdgeRange(convEdges); var algo = new BipartiteDimensionAlgorithm(g); algo.Compute(); return algo.BipartiteDimensionValue; }
public void IsEdgesEmptyGet211() { UndirectedGraph<int, Edge<int>> undirectedGraph; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; this.IsEdgesEmptyGet<int, Edge<int>>(undirectedGraph); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(0, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(0, undirectedGraph.EdgeCount); }
public static Pixel VertexSearch(int x, int y, UndirectedGraph<Pixel, TaggedUndirectedEdge<Pixel, EdgeTag>> graph) { return graph.Vertices.SingleOrDefault(o => o.y == y && o.x == x); /* foreach (var v in graph.Vertices) { //if (v.ToString() == Convert.ToString(x) + "-" + Convert.ToString(y)) if(v.x == x && v.y == y) return v; } return null; */ }
private List<List<int>> InducedPaths(int[] verticies, int[] edges) { var graph = new UndirectedGraph<int, IEdge<int>>(); graph.AddVertexRange(verticies); var graphEdges = new Edge<int>[edges.Length / 2]; for (int i = 0; i < edges.Length; i += 2) { graphEdges[i / 2] = new Edge<int>(edges[i], edges[i + 1]); } graph.AddEdgeRange(graphEdges); return InducedPathAlgorithm.findInducedPaths(graph); }
public void ContainsVertex913() { UndirectedGraph<int, Edge<int>> undirectedGraph; bool b; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; b = this.ContainsVertex<int, Edge<int>>(undirectedGraph, 0); Assert.AreEqual<bool>(false, b); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(0, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(0, undirectedGraph.EdgeCount); }
public void AddVertex24() { UndirectedGraph<int, Edge<int>> undirectedGraph; bool b; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = int.MinValue; b = this.AddVertex<int, Edge<int>>(undirectedGraph, 0); Assert.AreEqual<bool>(true, b); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(int.MinValue, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(0, undirectedGraph.EdgeCount); }
// effects: Given a list of cells, segments them into multiple // "groups" such that view generation (including validation) of one // group can be done independently of another group. Returns the // groups as a list (uses the foreign key information as well) internal List<CellGroup> GroupRelatedCells() { // If two cells share the same C or S, we place them in the same group // For each cell, determine the Cis and Sis that it refers // to. For every Ci (Si), keep track of the cells that Ci is // contained in. At the end, run through the Cis and Sis and do a // "connected components" algorithm to determine partitions // Now form a graph between different cells -- then compute the connected // components in it var graph = new UndirectedGraph<Cell>(EqualityComparer<Cell>.Default); var alreadyAddedCells = new List<Cell>(); // For each extent, add an edge between it and all previously // added extents with which it overlaps foreach (var cell in m_cells) { graph.AddVertex(cell); // Add an edge from this cell to the already added cells var firstCExtent = cell.CQuery.Extent; var firstSExtent = cell.SQuery.Extent; foreach (var existingCell in alreadyAddedCells) { var secondCExtent = existingCell.CQuery.Extent; var secondSExtent = existingCell.SQuery.Extent; // Add an edge between cell and existingCell if // * They have the same C or S extent // * They are linked via a foreign key between the S extents // * They are linked via a relationship var sameExtent = secondCExtent.Equals(firstCExtent) || secondSExtent.Equals(firstSExtent); var linkViaForeignKey = OverlapViaForeignKeys(cell, existingCell); var linkViaRelationship = AreCellsConnectedViaRelationship(cell, existingCell); if (sameExtent || linkViaForeignKey || linkViaRelationship) { graph.AddEdge(existingCell, cell); } } alreadyAddedCells.Add(cell); } // Now determine the connected components of this graph var result = GenerateConnectedComponents(graph); return result; }
public void ShouldAddNodes(string inodes) { //Arrange var expectedNodes = inodes.Split(nodeSeparator, StringSplitOptions.RemoveEmptyEntries) .Select(char.Parse) .OrderBy(x => x) .ToList(); AbstractGraph<char, int> sut = new UndirectedGraph<char, int>(); //Act expectedNodes.ForEach(x => sut.AddNode(x)); var actual = sut.GetNodes().OrderBy(x => x); //Assert Assert.AreEqual(expectedNodes, actual); }
public void RemoveVertexIf682() { UndirectedGraph<int, Edge<int>> undirectedGraph; int i; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; i = this.RemoveVertexIf<int, Edge<int>> (undirectedGraph, (VertexPredicate<int>)null); Assert.AreEqual<int>(0, i); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(0, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(0, undirectedGraph.EdgeCount); }
public void AddVertexRange796() { UndirectedGraph<int, Edge<int>> undirectedGraph; int i; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; int[] ints = new int[2]; i = this.AddVertexRange<int, Edge<int>>(undirectedGraph, (IEnumerable<int>)ints); Assert.AreEqual<int>(1, i); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(0, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(0, undirectedGraph.EdgeCount); }
private UndirectedGraph<int, int> GetGraph(int noOfNodes, int maxNoOfEdges) { var startTime = DateTime.UtcNow; var graph = new UndirectedGraph<int, int>(); var e = 0; for (int n = 1; n <= noOfNodes && e<= maxNoOfEdges; n++) { for (int i = n + 1; i <= noOfNodes && e <= maxNoOfEdges; i++, e++) { graph.AddEdge(n, i, 1); } } var endTime = DateTime.UtcNow; System.Diagnostics.Trace.WriteLine(String.Format("Completed graph construction in {0}",endTime. Subtract(startTime).TotalMilliseconds)); return graph; }
public static void Main() { var graph = new UndirectedGraph<int, Edge<int>>(); graph.AddVertex(1); graph.AddVertex(2); graph.AddVertex(3); graph.AddVertex(4); graph.AddEdge(new Edge<int>(1, 2)); graph.AddEdge(new Edge<int>(3, 4)); graph.AddEdge(new Edge<int>(1, 4)); foreach (var edge in graph.Edges) { Console.WriteLine(edge.Source + " " + edge.Target); } }
public void RemoveEdges327() { UndirectedGraph<int, Edge<int>> undirectedGraph; int i; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; Edge<int>[] edges = new Edge<int>[0]; i = this.RemoveEdges<int, Edge<int>> (undirectedGraph, (IEnumerable<Edge<int>>)edges); Assert.AreEqual<int>(0, i); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(0, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(0, undirectedGraph.EdgeCount); }
public void AddVerticesAndEdge242() { UndirectedGraph<int, Edge<int>> undirectedGraph; Edge<int> edge; bool b; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = int.MinValue; edge = EdgeFactory.Create(834, 584); b = this.AddVerticesAndEdge<int, Edge<int>>(undirectedGraph, edge); Assert.AreEqual<bool>(true, b); Assert.IsNotNull((object)undirectedGraph); Assert.IsNull(undirectedGraph.EdgeEqualityComparer); Assert.AreEqual<int>(int.MinValue, undirectedGraph.EdgeCapacity); Assert.AreEqual<bool>(false, undirectedGraph.IsDirected); Assert.AreEqual<bool>(false, undirectedGraph.AllowParallelEdges); Assert.AreEqual<int>(1, undirectedGraph.EdgeCount); }
public void TestAddEdge(object v1, object v2, int weight) { List <object> cities = new List <object>() { "Seattle", "LA", "Denver" }; //Set up the graph UndirectedGraph g = new UndirectedGraph(cities); //Add edge g.AddEdge(v1, v2, weight); //Assert success - that v1 is in the adjacency list of v2 and vice versa Dictionary <string, int> v1Neighbors = g.GetNeighbors(v1); Dictionary <string, int> v2Neighbors = g.GetNeighbors(v2); Assert.True(v1Neighbors.ContainsValue(weight) && v2Neighbors.ContainsValue(weight)); }
public void ThreeVerticeGraphHasOneEdgeEulerianTrail() { var sut = new FleurysAlgorithm(); var graph = new UndirectedGraph(3); graph.Connect(0, 1); graph.Connect(1, 2); Assert.Collection(sut.GetEulerianTrail(graph), arg => { Assert.Equal(2, arg.Item1); Assert.Equal(1, arg.Item2); }, arg => { Assert.Equal(1, arg.Item1); Assert.Equal(0, arg.Item2); }); }
public IsHamiltonianGraphAlgorithm(UndirectedGraph <TVertex, UndirectedEdge <TVertex> > graph) { // Create new graph without parallel edges var newGraph = new UndirectedGraph <TVertex, UndirectedEdge <TVertex> >(false, graph.EdgeEqualityComparer); foreach (var vertex in graph.Vertices) { newGraph.AddVertex(vertex); } foreach (var edge in graph.Edges) { newGraph.AddEdge(edge); } //Remove loops EdgePredicate <TVertex, UndirectedEdge <TVertex> > isLoop = e => e.Source.Equals(e.Target); newGraph.RemoveEdgeIf(isLoop); this.graph = newGraph; }
// Tested public static bool DFSSearch(int source, int destination, UndirectedGraph <int, Edge <int> > g, out List <Edge <int> > path) { var visited = new Dictionary <int, bool>(); foreach (var vertex in g.Vertices) { visited.Add(vertex, false); } var pathStack = new Stack <Edge <int> >(); bool pathFound = DFSSearchRecurse(source, destination, visited, g, pathStack); path = new List <Edge <int> >(); while (pathStack.Count != 0) { path.Add(pathStack.Pop()); } return(pathFound); }
private static void Bk(int[][] adjacencies, int[][] cliques) { var adjacencies2 = adjacencies.Select(neighbours => neighbours.Select(i => Vertex.Nth(i)).ToHashSet()) .ToImmutableArray(); var cliques2 = cliques.Select(clique => clique.Select(i => Vertex.Nth(i)).ToArray()).ToArray(); var graph = new UndirectedGraph(adjacencies2); foreach (var funcIndex in Enumerable.Range(0, Portfolio.FuncNames.Length)) { var reporter = new SimpleReporter(); Portfolio.Explore(funcIndex, graph, reporter); Assert.AreEqual(cliques2.Length, reporter.Cliques.Count); Portfolio.SortCliques(reporter.Cliques); foreach ((var reportedClique, var i) in reporter.Cliques.Select((v, i) => (v, i))) { Assert.That(reportedClique.SequenceEqual(cliques2[i])); } } }
// Testgraph 5 with missing edge between 2 and 5 public static UndirectedGraph <int, Edge <int> > TestGraph10() { var g = new UndirectedGraph <int, Edge <int> >(); g.AddVertexRange(new int[] { 0, 1, 2, 3, 4, 5 }); var edges = new List <Edge <int> > { new Edge <int>(0, 1), new Edge <int>(0, 2), new Edge <int>(1, 3), new Edge <int>(2, 3), new Edge <int>(3, 4), new Edge <int>(4, 5), }; g.AddEdgeRange(edges); return(g); }
public static List <UndirectedGraph <int, IEdge <int> > > Convert(string filepath) { StreamReader file = new StreamReader(filepath); List <UndirectedGraph <int, IEdge <int> > > graphs = new List <UndirectedGraph <int, IEdge <int> > >(); UndirectedGraph <int, IEdge <int> > currGraph = null;// = new UndirectedGraph<int, IEdge<int>>(); string line = file.ReadLine(); while (line != null) { if (string.IsNullOrWhiteSpace(line)) { line = file.ReadLine(); continue; } if (line.StartsWith("Graph")) { if (!(currGraph is null)) { graphs.Add(currGraph); } currGraph = new UndirectedGraph <int, IEdge <int> >(false); } else if (line.StartsWith(" ")) { string[] verts = line.Split(' ', ':', ';').Where(s => !string.IsNullOrEmpty(s)).ToArray(); int[] vertices = verts.Select(s => int.Parse(s)).ToArray(); currGraph.AddVertex(vertices[0]); for (int i = 1; i < vertices.Length; i++) { currGraph.AddVerticesAndEdge(new Edge <int>(vertices[0], vertices[i])); } } line = file.ReadLine(); } if (!(currGraph is null)) { graphs.Add(currGraph); } return(graphs); }
private (IGraph, Dictionary <string, int>) Load(string filePath, bool withAnonymization) { var graph = new UndirectedGraph(); var adjacencyList = ProcessRawData(filePath); var anonymizedNodePairMap = GetMapOfAnonymizedNodes(adjacencyList, withAnonymization); foreach (var nodePair in adjacencyList) { var nodeX = anonymizedNodePairMap[nodePair.Item1]; var nodeY = anonymizedNodePairMap[nodePair.Item2]; graph.AddBidirectionEdge(nodeX, nodeY); } return(graph, anonymizedNodePairMap); }
public void NoEdge_undirected_graph_components() { var nodes = new List <GraphNode <int> >() { new GraphNode <int>(0), new GraphNode <int>(1), new GraphNode <int>(2) }; var edges = new List <UndirectedEdge <int> >(); var graph = new UndirectedGraph <int>(nodes, edges); var componentAlgorithms = new GraphComponents <int>(); var connectedComponents = componentAlgorithms.DfsConnectedComponents(graph); Assert.Equal(0, connectedComponents[nodes[0]]); Assert.Equal(1, connectedComponents[nodes[1]]); Assert.Equal(2, connectedComponents[nodes[2]]); }
public DepthFirstCycle(UndirectedGraph graph) { if (graph == null || graph.Vertices == 0) { throw new ArgumentException(); } _graph = graph; _marked = new bool[graph.Vertices]; _hasCycle = false; for (var i = 0; i < graph.Vertices; i++) { if (!_marked[i]) { Search(i, i); } } }
public void TestGetNeighbors(int weight1, int weight2) { List <object> cities = new List <object>() { "Seattle", "LA", "Denver" }; //Set up the graph UndirectedGraph g = new UndirectedGraph(cities); //Add edge g.AddEdge(cities[0], cities[1], weight1); g.AddEdge(cities[2], cities[0], weight2); Dictionary <string, int> seattleNeighbors = g.GetNeighbors("Seattle"); Assert.True(seattleNeighbors.ContainsValue(weight1) && seattleNeighbors.ContainsValue(weight2)); }
private int Dfs(UndirectedGraph graph, int vertex, HashSet <int> visited, ref int count) { if (visited.Contains(vertex)) { return(count); } visited.Add(vertex); count += 1; foreach (int neighbor in graph.AdjList[vertex]) { Dfs(graph, neighbor, visited, ref count); } visited.Remove(vertex); return(count); }
/// <summary> /// verify graph connectivity for synchronously process /// </summary> /// <param name="n"></param> /// <param name="hashHeap"></param> /// <param name="hashToGraph"></param> private void SubGraphs(UndirectedGraph <IHash, Edge <IHash> > n, BinaryHeap <int, IHash> hashHeap, Dictionary <IHash, UndirectedGraph <IHash, Edge <IHash> > > hashToGraph) { // Bipartite Graph check Dictionary <IHash, int> colorDictionary = new Dictionary <IHash, int>(); foreach (var hash in n.Vertices) { if (colorDictionary.Keys.Contains(hash)) { continue; } UndirectedGraph <IHash, Edge <IHash> > subGraph = new UndirectedGraph <IHash, Edge <IHash> >(); // hash with most dependencies in the graph IHash maxHash = hash; bool isBipartite = DfsSearch(n, subGraph, ref maxHash, colorDictionary); if (isBipartite) { //TODO : if bipartite, parallel process for tasks in both sets asynchronously; /*foreach (var h in subGraph.Vertices) * { * if (colorDictionary[h]==1) * { * Console.Write("white:" + (char)h.GetHashBytes()[0]+" "); * } * if (colorDictionary[h]==-1) * { * Console.Write("black:" + (char)h.GetHashBytes()[0]+" "); * } * * }*/ continue; } //if not Bipartite, add maxhash to heap and hashToGraph Dictionary hashHeap.Add(subGraph.AdjacentDegree(maxHash), maxHash); hashToGraph[maxHash] = subGraph; } }
private static UndirectedGraph <int, Edge <int> > GetGraph1() { var g = new UndirectedGraph <int, Edge <int> >(); g.AddVertexRange(new List <int> { 0, 1, 2, 3, 4, 5 }); g.AddEdgeRange(new List <Edge <int> > { new Edge <int>(0, 1), new Edge <int>(0, 4), new Edge <int>(1, 2), new Edge <int>(1, 4), new Edge <int>(2, 3), new Edge <int>(2, 5), new Edge <int>(4, 5), }); return(g); }
/// <summary> /// Initializes a new instance of the <see cref="IsHamiltonianGraphAlgorithm{TVertex,TEdge}"/> class. /// </summary> /// <param name="graph">Graph to check.</param> public IsHamiltonianGraphAlgorithm(IUndirectedGraph <TVertex, TEdge> graph) { if (graph is null) { throw new ArgumentNullException(nameof(graph)); } // Create new graph without parallel edges var newGraph = new UndirectedGraph <TVertex, TEdge>( false, graph.EdgeEqualityComparer); newGraph.AddVertexRange(graph.Vertices); newGraph.AddEdgeRange(graph.Edges); newGraph.RemoveEdgeIf(edge => edge.IsSelfEdge()); _graph = newGraph; _threshold = newGraph.VertexCount / 2.0; }
public void GraphConstructionFromAdjMatrixTest2() { var adjMat = new AdjacencyMatrix(new[, ] { { false, true, false, true, true, false, false, false, false }, { true, false, true, true, true, true, false, false, false }, { false, true, false, false, true, true, false, false, false }, { true, true, false, false, true, false, true, true, false }, { true, true, true, true, false, true, true, true, true }, { false, true, true, false, true, false, false, true, true }, { false, false, false, true, true, false, false, true, false }, { false, false, false, true, true, true, true, false, true }, { false, false, false, false, true, true, false, true, false } }); var graph = new UndirectedGraph(adjMat); Assert.AreEqual(20, graph.EdgesCount); }
public void RemoveEdges_Throws() { int verticesRemoved = 0; int edgesRemoved = 0; var graph = new UndirectedGraph <int, Edge <int> >(); graph.VertexRemoved += v => { Assert.IsNotNull(v); ++verticesRemoved; }; graph.EdgeRemoved += e => { Assert.IsNotNull(e); ++edgesRemoved; }; var edge = new Edge <int>(1, 2); graph.AddVerticesAndEdge(edge); // ReSharper disable once AssignNullToNotNullAttribute Assert.Throws <ArgumentNullException>(() => graph.RemoveEdges(null)); AssertHasEdges(graph, new[] { edge }); CheckCounters(); Assert.Throws <ArgumentNullException>(() => graph.RemoveEdges(new[] { edge, null })); Assert.AreEqual(0, edgesRemoved); AssertHasEdges(graph, new[] { edge }); CheckCounters(); #region Local function void CheckCounters() { Assert.AreEqual(0, verticesRemoved); Assert.AreEqual(0, edgesRemoved); } #endregion }
// Dumb n^4 four-cycle finder public static List <int> FindFourCycle1(UndirectedGraph <int, Edge <int> > graph) { foreach (var v in graph.Vertices) { var vAdj = graph.AdjacentEdges(v).ToList(); for (int i = 0; i < vAdj.Count; i++) { for (int j = 0; j < vAdj.Count; j++) { if (i == j) { continue; } var vi = vAdj[i].Source == v ? vAdj[i].Target : vAdj[i].Source; var vj = vAdj[j].Source == v ? vAdj[j].Target : vAdj[j].Source; Edge <int> connectingEdge; graph.TryGetEdge(vi, vj, out connectingEdge); if (connectingEdge == null) { graph.TryGetEdge(vj, vi, out connectingEdge); } if (connectingEdge != null) //three cycle { continue; } var viAdj = new HashSet <int>(graph.AdjacentEdges(vi).Select(e => e.GetOtherVertex(vi))); var vjAdj = new HashSet <int>(graph.AdjacentEdges(vj).Select(e => e.GetOtherVertex(vj))); var common = new HashSet <int>(viAdj.Intersect(vjAdj)); common.Remove(v); if (common.Count > 0) { return new List <int> { v, vi, vj, common.First() } } ; } } } return(null); }
public void Constructor_Throws() { // ReSharper disable ObjectCreationAsStatement // ReSharper disable AssignNullToNotNullAttribute var graph = new UndirectedGraph <int, Edge <int> >(); var verticesColors = new Dictionary <int, GraphColor>(); var queue = new BinaryQueue <int, double>(_ => 1.0); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, queue, verticesColors)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(graph, null, verticesColors)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(graph, queue, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, null, verticesColors)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, queue, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(graph, null, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, null, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, null, queue, verticesColors)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, graph, null, verticesColors)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, graph, queue, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, null, null, verticesColors)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, null, queue, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, graph, null, null)); Assert.Throws <ArgumentNullException>( () => new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(null, null, null, null)); // ReSharper restore AssignNullToNotNullAttribute // ReSharper restore ObjectCreationAsStatement }
public String ToNewEdges(UndirectedGraph <Pixel, TaggedUndirectedEdge <Pixel, EdgeTag> > g, string fileName = "image.svg") { svg = new SVGDocument(Width * scale + 1, Height * scale + 1); foreach (var e in g.Edges) { if ((e.Tag.Visible)) { svg.DrawLine(Color.Black, 0.800, e.Source.x * scale + scale / 2, e.Source.y * scale + scale / 2, e.Target.x * scale + scale / 2, e.Target.y * scale + scale / 2); } } //Retorna o nome do arquivo salvo svg.Save(fileName); return(fileName); }
// Generates a new undirected graph using an adjacency matrix. public UndirectedGraph <int> GenerateUndirectedGraph(int size, float probability) { UndirectedGraph <int> graph = new UndirectedGraph <int>(size); System.Random rPos = new System.Random(); int[,] adjMat = GenerateAdjacencyMatrix(size, probability); for (int x = 0; x < size; x++) { if (x == 0) { graph.AddNode(new EntryNode(x, Vector3.zero)); } else if (x == size - 2) { graph.AddNode(new BossRoom(x, new Vector3(rPos.Next(x - 3, x + 3) * scale, 0, rPos.Next(x - 3, x + 3) * scale))); } else if (x == size - 1) { graph.AddNode(new ExitNode(x, new Vector3(rPos.Next(x - 3, x + 3) * scale, 0, rPos.Next(x - 3, x + 3) * scale))); } else { graph.AddNode(new RoomNode(x, new Vector3(rPos.Next(x - 3, x + 3) * scale, 0, rPos.Next(x - 3, x + 3) * scale))); } } for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { // int difference = Mathf.Abs(y) + x; if (adjMat[x, y] == 1 && !graph.Nodes[x].Neighbours.Contains(graph.Nodes[y])) { graph.Nodes[x].AddEdge(graph.Nodes[y]); } } } return(graph); }
public static Tuple <Player, int> GetLongestRoad(this GameState gameState) { var playerWithLongestRoad = new Tuple <Player, int>(null, 0); foreach (Player player in gameState.Players) { var playerOwnedEdges = gameState.AdjacencyGraph.Edges.Where(edge => edge.PlayerOwner == player); var playerGraph = new UndirectedGraph <BoardVertex, BoardEdge>(); playerGraph.AddVerticesAndEdgeRange(playerOwnedEdges); // Might need this for efficiency // var endpoints = playerGraph.Edges.Where(potentialEndpoint => // { // var sourceDegree = playerGraph.AdjacentDegree(potentialEndpoint.Source); // var targetDegree = playerGraph.AdjacentDegree(potentialEndpoint.Target); // return sourceDegree == 1 || targetDegree == 1; // }); // var edgesToCheck = endpoints.Count() > 0 ? endpoints : playerGraph.Edges; var longestPath = 0; foreach (BoardEdge edge in playerGraph.Edges) { var longestPathFromEndpoint = playerGraph.LongestPathDepthFirstSearch(player, edge); if (longestPath < longestPathFromEndpoint) { longestPath = longestPathFromEndpoint; } } if (longestPath >= 5 && (playerWithLongestRoad.Item1 == null || playerWithLongestRoad.Item2 < longestPath)) { playerWithLongestRoad = Tuple.Create(player, longestPath); } } return(playerWithLongestRoad); }
// weird subset of testgraph14 with added edges, where findcycle2 finds cycle and 3 does not public static UndirectedGraph <int, Edge <int> > TestGraph15() { var g = new UndirectedGraph <int, Edge <int> >(); g.AddVertexRange(new int[] { 22, 39, 95, 48, 73, 29, 65, 3, 68, 25, 30, 89, 85, 67, 18, 94, 72, 66, 62, 81, 20 }); var edges = new List <Edge <int> > { new Edge <int>(3, 22), new Edge <int>(73, 22), new Edge <int>(39, 29), new Edge <int>(39, 20), new Edge <int>(95, 85), new Edge <int>(30, 95), new Edge <int>(48, 66), new Edge <int>(48, 62), new Edge <int>(18, 48), new Edge <int>(3, 73), new Edge <int>(73, 62), new Edge <int>(89, 73), new Edge <int>(29, 85), new Edge <int>(94, 65), new Edge <int>(89, 65), new Edge <int>(65, 68), new Edge <int>(65, 3), new Edge <int>(68, 72), new Edge <int>(25, 66), new Edge <int>(18, 25), new Edge <int>(89, 25), new Edge <int>(81, 30), new Edge <int>(89, 94), new Edge <int>(72, 67), new Edge <int>(67, 20), new Edge <int>(18, 66), new Edge <int>(66, 62), new Edge <int>(81, 20) }; g.AddEdgeRange(edges); return(g); }
public static Tuple <int, HashSet <Edge <int> > > FindK(UndirectedGraph <int, Edge <int> > graph, DateTime timeOfInit) { int ret = -1; int k = -1; HashSet <Edge <int> > retEdges = null; while (ret == -1) { k++; var time1 = DateTime.Now; var clone = CloneGraph(graph); Console.WriteLine(k); var tup = FasterInner(clone, k, k * 2, new HashSet <int>(), null, null, new HashSet <Edge <int> >()); ret = tup.Item1; retEdges = tup.Item2; Console.WriteLine($"Took {(DateTime.Now - time1):c}"); Console.WriteLine($"Cumulated {(DateTime.Now - timeOfInit):c}"); } return(new Tuple <int, HashSet <Edge <int> > >(k - ret, retEdges)); }
public DepthFirstBipartite(UndirectedGraph graph) { if (graph == null || graph.Vertices == 0) { throw new ArgumentException(); } _graph = graph; _marked = new bool[graph.Vertices]; _color = new bool[graph.Vertices]; _isTwoColorable = true; for (int i = 0; i < graph.Vertices; i++) { if (!_marked[i]) { Search(i); } } }
public void AdjacentEdge_Throws() { var graph1 = new UndirectedGraph <int, Edge <int> >(); AdjacentEdge_Throws_Test( graph1, (vertexPredicate, edgePredicate) => new FilteredUndirectedGraph <int, Edge <int>, UndirectedGraph <int, Edge <int> > >( graph1, vertexPredicate, edgePredicate)); var graph2 = new UndirectedGraph <TestVertex, Edge <TestVertex> >(); var filteredGraph2 = new FilteredUndirectedGraph <TestVertex, Edge <TestVertex>, UndirectedGraph <TestVertex, Edge <TestVertex> > >( graph2, _ => true, _ => true); AdjacentEdge_NullThrows_Test(filteredGraph2); }
public void RemoveEdgeFromGraph_ShouldRemove() { var g = new UndirectedGraph <int, Edge <int> >(); var edges = GetGraph1().Edges; g.AddVerticesAndEdgeRange(edges); foreach (var edge in edges) { int originalGraphCount = g.EdgeCount; bool edgeRemoved = EdmondsAlgorithm.RemoveEdgeFromGraph(g, edge, out UndirectedGraph <int, Edge <int> > smallerGraph); g = smallerGraph; Assert.IsTrue(edgeRemoved, "Edge was not removed"); int edgesCountDifference = originalGraphCount - smallerGraph.EdgeCount; Assert.AreEqual(1, edgesCountDifference, $"Edges numbers are incorrect. " + $"Expected <{originalGraphCount}>. Actual <{smallerGraph.EdgeCount}>"); } }
public void Baseline() { var sut = new KargersAlgorithmForMinimumCut(); var graph = new UndirectedGraph(4); graph.Connect(0, 1); graph.Connect(0, 2); graph.Connect(1, 3); graph.Connect(1, 2); graph.Connect(2, 3); var minCut = int.MaxValue; while (minCut > 2) { minCut = sut.MinCut(graph); Assert.NotInRange(minCut, 0, 1); } }
public void AddEdgeTest() { string[] lines = File.ReadAllLines("MSTTestGraph.txt"); int n = int.Parse(lines[0].Split(' ')[0]); int m = int.Parse(lines[0].Split(' ')[1]); UndirectedGraph undirectedGraph = new UndirectedGraph(new MatrixRepresentation(n)); for (int i = 0; i < m; i++) { string[] tokens = lines[i + 1].Split(' '); int from = int.Parse(tokens[0]); int to = int.Parse(tokens[1]); double cost = double.Parse(tokens[2]); undirectedGraph.AddEdge(new Edge(from, to, cost)); } if (undirectedGraph.Edges != m) { Assert.Fail(); } }
public static void Main() { // ot Manage NuGet Packages- izpolzvame vanshna biblioteka; // https://quickgraph.codeplex.com/documentation var graph = new UndirectedGraph<int, Edge<int>>(); graph.AddVertex(1); graph.AddVertex(2); graph.AddVertex(3); graph.AddVertex(4); graph.AddEdge(new Edge<int>(1, 2)); graph.AddEdge(new Edge<int>(3, 4)); graph.AddEdge(new Edge<int>(1, 4)); foreach (var edge in graph.Edges) { Console.WriteLine(edge.Source + " " + edge.Target); } }
public void TestPathDoesNotExist() { List <object> nodes = new List <object>() { "Seattle", "Denver", "LA" }; string[] cities = { "Seattle", "Denver", "LA" }; //Create graph UndirectedGraph g = new UndirectedGraph(nodes); g.AddEdge("Seattle", "Denver", 300); g.AddEdge("Seattle", "LA", 200); Tuple <bool, int> result = Program.GetEdge(g, cities); Assert.True(result.Item1 == false && result.Item2 == 0); }
public void ContainsEdgeTest1() { var u = new UndirectedGraph<int, IEdge<int>>(); var e12 = new SEquatableUndirectedEdge<int>(1, 2); var f12 = new SEquatableUndirectedEdge<int>(1, 2); bool exceptionOccurred = false; try { new SEquatableUndirectedEdge<int>(2, 1); } catch (ArgumentException e) { exceptionOccurred = true; } Assert.IsTrue(exceptionOccurred); u.AddVerticesAndEdge(e12); ContainsEdgeAssertions(u, e12, f12, null, null); }
public void ShouldAutomaticallyAddNodesWhenAddingEdges(string iedges, string iexpectedNodes) { //Arrange var edges = ParseEdges(iedges).OrderBy(x => x.SourceNode).ThenBy(x => x.DestinationNode).ThenBy(x => x.Weight); var sut = new UndirectedGraph<char, int>(); var expectedNodes = iexpectedNodes.Split(nodeSeparator, StringSplitOptions.RemoveEmptyEntries) .Select(char.Parse) .OrderBy(x => x); //Act foreach (var edge in edges) { sut.AddEdge(edge.SourceNode, edge.DestinationNode, edge.Weight); } var actual = sut.GetNodes().OrderBy(x => x); //Assert Assert.AreEqual(expectedNodes, actual.Select(x => x)); }
public void RemoveEdgesThrowsKeyNotFoundException545() { UndirectedGraph<int, Edge<int>> undirectedGraph; Edge<int> edge; int i; undirectedGraph = new UndirectedGraph<int, Edge<int>> (false, (EdgeEqualityComparer<int, Edge<int>>)null); undirectedGraph.EdgeCapacity = 0; edge = EdgeFactory.Create(0, 0); Edge<int>[] edges = new Edge<int>[8]; edges[0] = edge; edges[1] = edge; edges[2] = edge; edges[3] = edge; edges[4] = edge; edges[5] = edge; edges[6] = edge; edges[7] = edge; i = this.RemoveEdges<int, Edge<int>> (undirectedGraph, (IEnumerable<Edge<int>>)edges); }