Friday, January 22, 2016

Leetcode: course scheule

// Class to represent a graph
class Graph
{
private:
    int V;    // No. of vertices'

    // Pointer to an array containing adjacency listsList
    vector> adj;
    vector result; // the order for vertics being sorted.
    vectorinDegree;
    int count;
public:
    Graph(int _V)// Constructor
    {
        V = _V;
        adj = vector>(V);
        inDegree = vector(V,0);
        count = 0;
    };  

    // function to add an edge to graph
    void addEdge(int v, int w)
    {
        adj[w].push_back(v);
        inDegree[v]++;
    };

    // prints a Topological Sort of the complete graph
    void topologicalSort()
    {
        // find all in_degree==0, and mark them as visited(set inDegree to -1)
        queue stack;
        for(int i=0; i            if(!inDegree[i]){
                stack.push(i);
                result.push_back(i);
                inDegree[i]=-1; // maked as visited
                count++;
            }
        }
        // pop a node from queue, decrease the degree of the neighbours and push the degree==0   
        while(!stack.empty()){
            int cur=stack.front();
            stack.pop();
            for(int i=0; i                inDegree[adj[cur][i]]--;
                if(inDegree[adj[cur][i]]==0){
                    count++;
                    stack.push(adj[cur][i]);
                    result.push_back(adj[cur][i]);
                    inDegree[adj[cur][i]]=-1;
                }
            }
        }
    };
  
    vector output()
    {
        if(count==V)    return result;
        else return vector();
    }
};



class Solution {
public:
    vector findOrder(int numCourses, vector>& prerequisites) {
        Graph  graph(numCourses);
        vector result;
        for(auto it = prerequisites.begin();it!=prerequisites.end();it++ )
            graph.addEdge((*it).first,(*it).second);
           
        graph.topologicalSort(); // sorting
      
        result = graph.output();
        return result;
    }
};

No comments: