def test_connected_components_directed(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') connected_components = sorted([ sorted(component) for component in graph.get_connected_components() ]) answer = sorted([ sorted(['A', 'B', 'C']), sorted(['D', 'E', 'F', 'G', 'H']), ]) self.assertListEqual(connected_components, answer)
def test_get_connected_components(self): """Get connected components of a graph.""" graph = Graph(is_directed=False) vertex_a = graph.add_vertex('A') vertex_b = graph.add_vertex('B') vertex_c = graph.add_vertex('C') vertex_d = graph.add_vertex('D') vertex_d = graph.add_vertex('E') vertex_d = graph.add_vertex('F') graph.add_edge('A', 'B') graph.add_edge('A', 'C') graph.add_edge('B', 'C') graph.add_edge('D', 'E') expected_components = [['A', 'B', 'C'], ['D', 'E'], ['F']] # sort each component for ease of comparison actual_components = graph.get_connected_components() actual_components = [sorted(comp) for comp in actual_components] self.assertCountEqual(expected_components, actual_components)
# 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())