How To Make Directed Graph In Python Leetcode

To create a directed graph in Python for LeetCode problems, you typically use a dictionary (hash map) to represent the graph. Each key in the dictionary represents a node, and its corresponding value is a list of nodes it’s connected to. Here’s a step-by-step guide on how to implement this:

  1. Create the graph structure:
def create_graph(n, edges):
    graph = {i: [] for i in range(n)}  # Initialize empty adjacency list for each node
    for start, end in edges:
        graph[start].append(end)
    return graph

2. Example usage:

# Example
n = 4  # Number of nodes
edges = [[0,1], [0,2], [1,3], [2,3]]  # List of directed edges

graph = create_graph(n, edges)
print(graph)

This will create a graph representation that you can use in various LeetCode problems involving directed graphs.

class Solution:
    def create_graph(self, n, edges):
        graph = {i: [] for i in range(n)}
        for start, end in edges:
            graph[start].append(end)
        return graph
    
    def dfs(self, node, graph, visited, result):
        if node not in visited:
            visited.add(node)
            result.append(node)
            for neighbor in graph[node]:
                self.dfs(neighbor, graph, visited, result)
    
    def traverse_graph(self, n, edges):
        graph = self.create_graph(n, edges)
        visited = set()
        result = []
        
        for node in range(n):
            if node not in visited:
                self.dfs(node, graph, visited, result)
        
        return result

# Example usage
if __name__ == "__main__":
    solution = Solution()
    n = 4
    edges = [[0,1], [0,2], [1,3], [2,3]]
    
    traversal_result = solution.traverse_graph(n, edges)
    print("Graph traversal result:", traversal_result)

This example includes:

  1. A create_graph function to build the graph structure.
  2. A depth-first search (DFS) implementation to traverse the graph.
  3. A traverse_graph method that creates the graph and performs a full traversal.
  4. An example usage of the implemented graph and traversal.

This code structure is common in LeetCode problems involving directed graphs. You can modify the traverse_graph method or add other methods as needed for specific problem requirements.