Tutorialspoint
Problem
Solution
Submissions

Implement a Graph Data Structure Using Adjacency List

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Create a Python class called Graph that implements a graph data structure using an adjacency list. The class should support directed and undirected graphs, adding and removing vertices and edges, and traversing the graph using breadth-first search (BFS) and depth-first search (DFS) algorithms.

Example 1
  • Input: graph = Graph()
  • Output: ["B", "C"]
  • Explanation:
    • Step 1: Create a new Graph instance.
    • Step 2: Add vertices and edges to form connections between nodes.
    • Step 3: Perform BFS or DFS starting from a given node.
    • Step 4: Return the list of nodes in the order visited.
Example 2
  • Input: graph = Graph()
  • Output: ["A", "B", "D", "C"]
  • Explanation:
    • Step 1: Initialize the Graph and add nodes and edges.
    • Step 2: Run a traversal method like DFS from node "A".
    • Step 3: The traversal visits nodes in the specified order.
Constraints
  • Vertices can be of any hashable data type
  • Time Complexity: O(1) for adding vertices and edges; O(V+E) for traversals
  • Space Complexity: O(V+E)
  • The graph should handle operations on non-existent vertices gracefully
Hash MapGraphDictionaries Google
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a dictionary to store the adjacency list with vertices as keys and a list or set of adjacent vertices as values
  • Implement methods for adding and removing vertices and edges
  • For BFS, use a queue to keep track of vertices to visit
  • For DFS, use a stack or recursion to keep track of vertices to visit
  • Use a set to keep track of visited vertices during traversals
  • Consider supporting weighted edges by using a tuple or custom Edge class
  • Consider implementing additional algorithms like shortest path or cycle detection

Steps to solve by this approach:

 Step 1: Create a Graph class with a dictionary to store the adjacency list.

 Step 2: Implement add_vertex and add_edge methods to build the graph structure.
 Step 3: Implement remove_edge and remove_vertex methods for graph modification.
 Step 4: Implement helper methods like get_neighbors and display.
 Step 5: Test the implementation with various graph operations.

Submitted Code :