Given an directed graph, a topological order of the graph nodes is defined as follow:
- For each directed edge A-->B in graph, A must before B in the order list.
- The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.
Note
You can assume that there is at least one topological order in the graph.
Example
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
or
[0, 2, 3, 1, 5, 4]
or
...
/*class Solution {
public:
vector<int> topSort(vector<vector<int>> &graph) {
int n = graph.size();
vector<int> output(n, 0);
vector<int> tasksReady(n);
vector<int> ancestorsCount(n, 0);
for(int i = 0; i < n; i++){
for(int j =0; j < graph[i].size(); j++)
if ( i != graph[i][j])
ancestorsCount[graph[i][j]]++;
}
int next = 0;
for(int i= 0; i < n; i++)
if (ancestorsCount[i] == 0)
tasksReady[next++] = i;
for(int i = 0; i < n; i++) {
int readyTaskId = tasksReady[i];
output[i] = readyTaskId;
for(int j =0; j < graph[readyTaskId].size(); j++) {
if(--ancestorsCount[graph[readyTaskId][j]] == 0)
tasksReady[next++] = graph[readyTaskId][j];
}
}
return output;
}
};
*/
class Solution {
public:
/**
* @param graph: A list of lists of integer
* @graph[i][j] is the edge(i, j)
* @return: A list of integer
*/
vector<int> topSort(vector<vector<int>> &graph) {
int n = graph.size();
vector<int> output;
vector<bool> scheduled(n, false);
vector<vector<int>> ancestors(n);
for(int i = 0; i < n; i++){
for(int j =0; j < graph[i].size(); j++)
ancestors[graph[i][j]].push_back(i);
}
for(int i = 0; i < n; i++) {
helper(ancestors, scheduled, i, output);
}
return output;
}
private:
void helper(vector<vector<int>> &ancestors, vector<bool> &scheduled, int current, vector<int> &output)
{
if (scheduled[current])
return;
scheduled[current] = true;
for(int ancestor: ancestors[current])
helper(ancestors, scheduled, ancestor, output);
output.push_back(current);
}
};
No comments:
Post a Comment