muhtalhakhan / Hacktoberfest2023

Hacktoberfest 2023 🧑🏻‍💻 OPEN FIRST Pull Request 🎉
https://www.hacktoberfest.com
GNU General Public License v3.0
13 stars 90 forks source link

Add topological sort in any language #24

Open muhtalhakhan opened 11 months ago

muhtalhakhan commented 11 months ago

If you like to do it then please comment

Abdul25Basit commented 11 months ago

i am interested

muhtalhakhan commented 11 months ago

Assigned.

Teerthesh706 commented 10 months ago

I am interested

AyusGup commented 10 months ago

i am interested

Mani1881 commented 10 months ago

hey @muhtalhakhan can u please assign this issue to me. import java.util.*;

class Graph { private int V; // Number of vertices private LinkedList[] adj; // Adjacency list

public Graph(int v) {
    V = v;
    adj = new LinkedList[v];
    for (int i = 0; i < v; i++) {
        adj[i] = new LinkedList<>();
    }
}

public void addEdge(int v, int w) {
    adj[v].add(w);
}

// Topological Sort using DFS
private void topologicalSortUtil(int v, boolean[] visited, Stack<Integer> stack) {
    visited[v] = true;
    for (Integer neighbor : adj[v]) {
        if (!visited[neighbor]) {
            topologicalSortUtil(neighbor, visited, stack);
        }
    }
    stack.push(v);
}

public void topologicalSort() {
    Stack<Integer> stack = new Stack<>();
    boolean[] visited = new boolean[V];

    for (int i = 0; i < V; i++) {
        if (!visited[i]) {
            topologicalSortUtil(i, visited, stack);
        }
    }

    while (!stack.isEmpty()) {
        System.out.print(stack.pop() + " ");
    }
}

public static void main(String[] args) {
    Graph graph = new Graph(6);
    graph.addEdge(5, 2);
    graph.addEdge(5, 0);
    graph.addEdge(4, 0);
    graph.addEdge(4, 1);
    graph.addEdge(2, 3);
    graph.addEdge(3, 1);

    System.out.println("Topological Sort:");
    graph.topologicalSort();
}

}