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 4cde96a

Browse files
Graph Implementation
1 parent 6347228 commit 4cde96a

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

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

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,25 @@
22
The Implementation will be same as Directed Graph, but this time the connection will be done both ways.
33
If v1 => v2 then v2 => v1
44
Or v1 <=> v2
5-
'''
5+
'''
6+
7+
# Simple Graph Implementation
8+
9+
class Graph:
10+
def __init__(self, number_of_nodes): # Initialise Graph Data Structure
11+
self.number_of_nodes = number_of_nodes + 1 # Number of nodes will have to be increased by one
12+
self.graph = [[0 for x in range(number_of_nodes + 1)] for y in range(number_of_nodes + 1)]
13+
14+
def withInBounds(self, v1, v2): # Function to check if the value is within matrix bounds
15+
return v1 >= 0 and v1 <= self.number_of_nodes and v2 >= 0 and v2 <= self.number_of_nodes
16+
17+
def insertEdge(self, v1, v2): # Function to inser edge in the Graph
18+
if self.withInBounds(v1, v2): # Check if values are within bounds
19+
self.graph[v1][v2] = 1 # Change the value of the node from 0 to 1
20+
self.graph[v2][v1] = 1 # Adding the two way relation between the vertices to make in undirected
21+
22+
def printGraph(self): # Functipon to Print Graph
23+
for i in range(self.number_of_nodes):
24+
for j in range(len(self.graph[i])):
25+
if self.graph[i][j]:
26+
print(i, '=>', j)

0 commit comments

Comments
(0)

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