topological Sort

 #include <iostream>

#include <stack>
#define M 20

using namespace std;

class Graph {
public:
    int V;
    int adj[M][M];
    bool visited[M];

    Graph(int vertices) {
        V = vertices;
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                adj[i][j] = 0; // Initialize adjacency matrix with zeros
            }
            visited[i] = false; // Initialize visited array as false
        }
    }

    void dfs(int v, stack<int>& s) {
        visited[v] = true;
       
        // Explore adjacent vertices
        for (int i = 0; i < V; i++) {
            if (adj[v][i] == 1 && !visited[i]) {
                dfs(i, s);
            }
        }

        s.push(v); // Push the vertex onto the stack upon completion
    }

    void topologicalSort() {
        stack<int> s;

        // Initialize the visited array
        for (int i = 0; i < V; i++) {
            visited[i] = false;
        }

        // Start DFS from each unvisited vertex
        for (int i = 0; i < V; i++) {
            if (!visited[i]) {
                dfs(i, s);
            }
        }

        // Output the vertices in topological order
        cout << "Topological Sorting: ";
        while (!s.empty()) {
            int v = s.top();
            s.pop();
            cout << v << " "; // Output the topological order
        }
        cout << endl;
    }
};

int main() {
    int v; // Number of vertices
    cout << "Enter the number of vertices: ";
    cin >> v;

    Graph g(v);

    cout << "Enter the adjacency matrix:" << endl;
    for (int i = 0; i < v; i++) {
        for (int j = 0; j < v; j++) {
            cin >> g.adj[i][j]; // Read the adjacency matrix
        }
    }

    // Perform topological sorting
    g.topologicalSort();

    return 0;
}

Comments

Popular Posts