How to Create a Sample Directed Graph and Implement Topological Sort in Code?

Question

How can I create a sample directed graph in code and implement a topological sort algorithm?

# Sample Python code for creating a directed graph and performing topological sort
from collections import defaultdict

class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    
    def add_edge(self, u, v):
        self.graph[u].append(v)
    
    def topological_sort_util(self, v, visited, stack):
        visited[v] = True
        
        for node in self.graph[v]:
            if not visited[node]:
                self.topological_sort_util(node, visited, stack)
        stack.append(v)
    
    def topological_sort(self):
        visited = {node: False for node in self.graph}
        stack = []

        for node in self.graph:
            if not visited[node]:
                self.topological_sort_util(node, visited, stack)
        print(stack[::-1]) # reversed stack for topological order

# Using the Graph class
g = Graph()
g.add_edge(5, 2)
g.add_edge(5, 0)
g.add_edge(4, 0)
g.add_edge(4, 1)
g.add_edge(2, 3)
g.add_edge(3, 1)

g.topological_sort()

Answer

Creating a directed graph and implementing a topological sort involves understanding both data structures and algorithms. A directed graph is composed of vertices and edges, where each edge has a direction. Topological sorting is an ordering of the vertices such that for every directed edge from vertex u to vertex v, u comes before v in the ordering.

from collections import defaultdict

class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    
    def add_edge(self, u, v):
        self.graph[u].append(v)
    
    def topological_sort_util(self, v, visited, stack):
        visited[v] = True
        
        for node in self.graph[v]:
            if not visited[node]:
                self.topological_sort_util(node, visited, stack)
        stack.append(v)
    
    def topological_sort(self):
        visited = {node: False for node in self.graph}
        stack = []

        for node in self.graph:
            if not visited[node]:
                self.topological_sort_util(node, visited, stack)
        print(stack[::-1]) # reversed stack for topological order

# Example usage
g = Graph()
g.add_edge(5, 2)
g.add_edge(5, 0)
g.add_edge(4, 0)
g.add_edge(4, 1)
g.add_edge(2, 3)
g.add_edge(3, 1)

g.topological_sort()

Causes

  • Misunderstanding of graph structures
  • Incorrect implementation of sorting logic

Solutions

  • Use depth-first search (DFS) to traverse the graph
  • Utilize a stack to store the sorted elements
  • Check for cycles in the graph before sorting

Common Mistakes

Mistake: Not handling cycles in the graph properly

Solution: Before performing topological sort, ensure the graph is acyclic.

Mistake: Confusing directed and undirected graphs

Solution: Clarify the type of graph you are working with; directed graphs require different handling.

Helpers

  • directed graph
  • topological sort
  • graph algorithms
  • data structures
  • Python graph implementation
  • DFS topological sort

Related Questions

⦿How to Download Source Code for a Specific JAR Dependency in a Maven Project

Learn how to download source code for a JAR dependency in a Maven project. Stepbystep guide and related tips included.

⦿How to Read JPEG File Attributes Using Java

Learn how to read and extract JPEG file attributes in Java with our detailed guide including code examples and common mistakes.

⦿How to Retrieve the Rendered Height of WebView Content in Android

Learn how to get the height of content in WebView once rendered in Android applications. Stepbystep guide with code snippets included.

⦿How to Handle Underscores with XStream Serialization

Learn how to manage underscores in field names when using XStream for XML serialization in Java.

⦿How to Check If a Server is Online Using Java Code

Learn how to check if a server is online with Java code. Explore code snippets common mistakes and expert tips.

⦿What Is the Best Data Type in Java for Storing Prices?

Explore the best data types in Java for accurately handling monetary values. Discover insights on precision and performance.

⦿How to Configure JPA with an Alternative `persistence.xml`

Learn how to set up JPA using a custom persistence.xml file for enhanced configuration options and flexibility.

⦿How to Create a Vertical Layout in Java?

Learn how to create a vertical layout in Java using layout managers such as BoxLayout and GridBagLayout.

⦿How to Import a JAR File into IntelliJ IDEA: A Step-by-Step Guide

Learn how to easily import JAR files into IntelliJ IDEA with this comprehensive guide and troubleshooting tips.

⦿How to Convert a List of Maps to a Single Map Using Java Streams?

Learn how to efficiently convert a list of maps into a single map in Java using streams along with examples and common pitfalls.

© Copyright 2025 - CodingTechRoom.com