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