Skip to main content
Practice

Graph Implementation Techniques

1. Defining the Graph Class

  • A graph is a data structure that models a network using nodes and edges.

  • The Graph class includes a dictionary to store nodes and their adjacent nodes.


Example Definition of Graph Class
class Graph:
def __init__(self):
self.graph = {} # Dictionary to store nodes and their adjacent nodes

2. Method to Add Edges

  • The add_edge method adds a bidirectional edge between two nodes.

  • If a node is not present in the graph, the node is added with an empty list assigned.


Example Method to Add Edges
def add_edge(self, node1, node2):
if node1 not in self.graph:
self.graph[node1] = []
if node2 not in self.graph:
self.graph[node2] = []

self.graph[node1].append(node2)
self.graph[node2].append(node1)

3. Graph Display Method

  • The display method outputs the contents of the graph.

  • By printing each node and its adjacent nodes, the method illustrates the structure of the graph.


Example Graph Display Method
def display(self):
for node in self.graph:
print(f"{node} -> {self.graph[node]}")

4. Creating and Using a Graph Object

  • Create an instance of the Graph class, and build the graph by adding edges.

  • Call the display method to verify the structure of the graph.


Example of Creating and Using a Graph Object
# Creating a graph object
g = Graph()

# Adding edges
g.add_edge('A', 'B')
g.add_edge('A', 'C')
g.add_edge('B', 'C')
g.add_edge('B', 'D')

# Displaying the graph
g.display()

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.