Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6025882

Browse files
Graph Implementation
1 parent c683199 commit 6025882

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

‎Data-Structures-and-Algorithms/Undirected-Graph-using-Adjacency-List.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,26 @@
66
The Implementation will be same as Directed Graph, but this time the connection will be done both ways.
77
If v1 => v2 then v2 => v1
88
Or v1 <=> v2
9-
'''
9+
'''
10+
11+
# Simple Directed Graph
12+
13+
class Graph:
14+
def __init__(self): # Initialise Graph
15+
self.graph = {}
16+
17+
def insertEdge(self, val1, val2): # Insert Edge in the Graph
18+
if val1 in self.graph: # Check if vertex already exists
19+
self.graph[val1].append(val2) # Append the list directed by the vertex
20+
else:
21+
self.graph[val1] = [val2] # Add new vertex if doesn't exist
22+
23+
if val2 in self.graph: # Additional Connection for Undirected Graph (Or directing both ways v1 <=> v2)
24+
self.graph[val2].append(val1)
25+
else:
26+
self.graph[val2] = [val1]
27+
28+
def printGraph(self): # Print Graph
29+
for node in self.graph:
30+
for val in self.graph[node]:
31+
print(node, ' => ', val) # Loop through the dictionary and print each node and the node that it is pointing to

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /