1. Graph representation using Adjacency Matrix
Graph Representation using Adjacency Matrix¶
In [1]:
Copied!
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
Graph¶
Graph
0---1
| /
| /
|/
2---3
Expected Matrix
[
[0, 1, 1, 0]
[1, 0, 1, 0]
[1, 1, 0, 1]
[0, 0, 1, 0]
]
Using Adjacency Matrix¶
In [2]:
Copied!
def graph_using_adjacency_matrix(n=4):
adjacency_matrix = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
u, v = map(int, input().split())
adjacency_matrix[u][v] = 1
adjacency_matrix[v][u] = 1
return np.array(adjacency_matrix)
def graph_using_adjacency_matrix(n=4):
adjacency_matrix = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
u, v = map(int, input().split())
adjacency_matrix[u][v] = 1
adjacency_matrix[v][u] = 1
return np.array(adjacency_matrix)
In [3]:
Copied!
graph_using_adjacency_matrix()
graph_using_adjacency_matrix()
Out[3]:
array([[0, 1, 1, 0], [1, 0, 1, 0], [1, 1, 0, 1], [0, 0, 1, 0]])
Using NetworkX¶
In [26]:
Copied!
class GraphVisualization:
def __init__(self):
# visual is a list which stores all
# the set of edges that constitutes a
# graph
self.visual = []
# addEdge function inputs the vertices of an
# edge and appends it to the visual list
def addEdge(self, a, b):
temp = [a, b]
self.visual.append(temp)
# In visualize function G is an object of
# class Graph given by networkx G.add_edges_from(visual)
# creates a graph with a given list
# nx.draw_networkx(G) - plots the graph
# plt.show() - displays the graph
def visualize(self):
G = nx.Graph()
G.add_edges_from(self.visual)
nx.draw_networkx(G)
plt.show()
class GraphVisualization:
def __init__(self):
# visual is a list which stores all
# the set of edges that constitutes a
# graph
self.visual = []
# addEdge function inputs the vertices of an
# edge and appends it to the visual list
def addEdge(self, a, b):
temp = [a, b]
self.visual.append(temp)
# In visualize function G is an object of
# class Graph given by networkx G.add_edges_from(visual)
# creates a graph with a given list
# nx.draw_networkx(G) - plots the graph
# plt.show() - displays the graph
def visualize(self):
G = nx.Graph()
G.add_edges_from(self.visual)
nx.draw_networkx(G)
plt.show()
In [28]:
Copied!
G = GraphVisualization()
G.addEdge(0, 1)
G.addEdge(0, 2)
G.addEdge(1, 2)
G.addEdge(2, 3)
G.visualize()
G = GraphVisualization()
G.addEdge(0, 1)
G.addEdge(0, 2)
G.addEdge(1, 2)
G.addEdge(2, 3)
G.visualize()
In [ ]:
Copied!