
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
Editorial
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. |
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