|
| 1 | +''' |
| 2 | +Overview: |
| 3 | +Edges connecting Verticies (basically nodes) |
| 4 | +Basically drawing a polygon. |
| 5 | +You can also have weighted edges (like NN) |
| 6 | +Or Directional/Bidirectional edges |
| 7 | +
|
| 8 | +Trees are a form of a graph, with a limitation of only 2 edges per node |
| 9 | +Linked Lists are a form of a graph with only one edge per node |
| 10 | +
|
| 11 | +Adjacency Matrix: |
| 12 | +Bidirectional graphs are mirrored along the main diagonal. |
| 13 | +Main diagonal is always 0 because no vertex can have an edge with itself. |
| 14 | +Weights can be stored in the matrix with the edges |
| 15 | +
|
| 16 | +Adjacency List: |
| 17 | +{ |
| 18 | +'A': ['B', 'E'], <-- Vertex A has edges with B and E |
| 19 | +'B': ['A', 'C'], |
| 20 | +. |
| 21 | +. |
| 22 | +. |
| 23 | +} |
| 24 | +
|
| 25 | +Big O: |
| 26 | +Space: O(n^2) Matrix, O(V + E) |
| 27 | +Adding a Vertex w/o edges: Add a new row/column O(V^2) Matrix, O(1) List |
| 28 | +Add an edge: O(1) Matrix, O(1) List |
| 29 | +Remove an edge: O(1) Matrix, O(E) List to find each edge in the edge list |
| 30 | +Remove a vertex: O(V^2) to remove row and column Matrix, O(V + E) List because you need to change every vertex list |
| 31 | +''' |
| 32 | + |
| 33 | + |
| 34 | +class Graph: |
| 35 | + def __init__(self): |
| 36 | + self.adj_list = {} |
| 37 | + |
| 38 | + def print_graph(self): |
| 39 | + for vertex in self.adj_list: |
| 40 | + print(vertex, ": ", self.adj_list[vertex]) |
| 41 | + |
| 42 | + def add_vertex(self, vertex): |
| 43 | + if vertex not in self.adj_list: |
| 44 | + self.adj_list[vertex] = [] |
| 45 | + return True |
| 46 | + return False |
| 47 | + |
| 48 | + def add_edge(self, v1, v2): |
| 49 | + if v1 in self.adj_list and v2 in self.adj_list: |
| 50 | + self.adj_list[v1].append(v2) |
| 51 | + self.adj_list[v2].append(v1) |
| 52 | + return True |
| 53 | + return False |
| 54 | + |
| 55 | + def remove_edge(self, v1, v2): |
| 56 | + if v1 in self.adj_list and v2 in self.adj_list: |
| 57 | + try: |
| 58 | + self.adj_list[v1].remove(v2) |
| 59 | + self.adj_list[v2].remove(v1) |
| 60 | + except ValueError: |
| 61 | + return False |
| 62 | + return True |
| 63 | + return False |
| 64 | + |
| 65 | + def remove_vertex(self, vertex): |
| 66 | + # You can remove edges specified in dict bc bidirectional |
| 67 | + if vertex in self.adj_list: |
| 68 | + for other_vertex in self.adj_list[vertex]: |
| 69 | + self.adj_list[other_vertex].remove(vertex) |
| 70 | + del self.adj_list[vertex] |
| 71 | + return True |
| 72 | + return False |
0 commit comments