def test_has_cycle(self): """Create a graph.""" graph = Graph(is_directed=True) graph.add_vertex('A') graph.add_vertex('B') graph.add_vertex('C') graph.add_vertex('D') graph.add_vertex('E') graph.add_vertex('F') graph.add_vertex('G') graph.add_vertex('H') graph.add_edge('A', 'B') graph.add_edge('B', 'C') graph.add_edge('C', 'A') graph.add_edge('D', 'E') graph.add_edge('E', 'F') graph.add_edge('G', 'H') graph.add_edge('G', 'F') self.assertEqual(True, graph.contains_cycle())
def test_does_contain_cycle(self): graph = Graph(is_directed=True) graph.add_vertex('A') graph.add_vertex('B') graph.add_vertex('C') graph.add_edge('A', 'B') graph.add_edge('B', 'C') graph.add_edge('C', 'A') self.assertTrue(graph.contains_cycle())
def test_does_not_contain_cycle_dag(self): """Test that a DAG does not contain a cycle.""" graph = Graph(is_directed=True) graph.add_vertex('A') graph.add_vertex('B') graph.add_vertex('C') graph.add_edge('A', 'B') graph.add_edge('B', 'C') graph.add_edge('A', 'C') self.assertFalse(graph.contains_cycle())
def test_contains_cycle_undirected(self): graph = Graph(is_directed=False) graph.add_vertex('A') graph.add_vertex('B') graph.add_vertex('C') graph.add_edge('A','B') graph.add_edge('B','C') graph.add_edge('C','A') # This would be true if graph were directed self.assertTrue(graph.contains_cycle())
def test_does_not_contain_cycle_tree(self): """Test that a tree on 4 vertices does not contain a cycle.""" graph = Graph(is_directed=True) vertex_a = graph.add_vertex('A') vertex_b = graph.add_vertex('B') vertex_c = graph.add_vertex('C') vertex_d = graph.add_vertex('D') graph.add_edge('A', 'B') graph.add_edge('A', 'C') graph.add_edge('A', 'D') self.assertFalse(graph.contains_cycle())
# Print vertices print(f'The vertices are: {graph.get_vertices()} \n') # Print edges print('The edges are:') # for vertex_obj in graph.get_vertices(): # for neighbor_obj in vertex_obj.get_neighbors(): # print(f'({vertex_obj.get_id()} , {neighbor_obj.get_id()})') print(graph.get_edges()) # Search the graph print('Performing BFS traversal...') graph.bfs_traversal('A') # Find shortest path print('Finding shortest path from vertex A to vertex E...') shortest_path = graph.find_shortest_path('A', 'E') print(shortest_path) # Find all vertices N distance away print('Finding all vertices distance 2 away...') vertices_2_away = graph.find_vertices_n_away('A', 2) print(vertices_2_away) print(graph.get_connected_components()) # print(graph.dfs_traversal('A')) print("!!!") print(graph.contains_cycle())