Adjacency Matrix (Graph) in Python
Adjacency matrix is a widely used graph data structure used to store graph. Couple of days ago I had to write a Python code that reads user input from console and stores the graph in an adjacency matrix. I used List for this purpose. Here is my code:-
Let me know if you have any other idea to represent a graph using adjacency matrix in Python.
def graph_input():
V = int(raw_input("Enter the number of Nodes: "))
E = int(raw_input("Enter the number of Edges: "))
print "Enter Edges with weights:\n"
adj_matrix = []
# vertex numbering starts from 0
for i in range(0, V):
temp = []
for j in range(0, V):
temp.append(0)
adj_matrix.append(temp)
for i in range(0, E):
s = raw_input()
u, v, w = s.split()
u = int(u)
v = int(v)
w = int(w)
adj_matrix[v][u] = adj_matrix[u][v] = w
# print the adjacency matrix
for i in range (0, V):
print adj_matrix[i]
return adj_matrix
graph = graph_input()
Let me know if you have any other idea to represent a graph using adjacency matrix in Python.
Comments
(u = 2, v = 4, w (weight) = 10)
I tried to find a python code for that but found nothing on that.
Any help in this regards will be highly appreciated.
## Creation of a random adjacency matrix
from random import randrange
n = 10
G = [[randrange(2) for i in range(n)] for i in range(n)]
##Those lines create a 10 X 10 random adjacency matrix filled with zeros and '1's.
## Hope it is worth knowing