Graph: Topological Sort
207. Course Schedule
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
class Solution {
public:
using graph_t = vector<unordered_set<int>>;
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
graph_t graph(numCourses);
vector<int> degree(graph.size());
queue<int> zeros;
for (auto course : prerequisites) graph[course.second].insert(course.first);
for (auto v : graph)
for (auto w : v)
degree[w]++;
for (int j = 0; j < numCourses; ++j)
if (degree[j] == 0) zeros.push(j);
while (!zeros.empty()) {
auto cur = zeros.front(); zeros.pop();
numCourses--;
for (auto v : graph[cur]) {
if (--degree[v] == 0) zeros.push(v);
}
}
return numCourses == 0;
}
};
210. Course Schedule II
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
class Solution {
public:
using graph_t = vector<unordered_set<int>>;
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
graph_t graph(numCourses);
vector<int> degrees(numCourses);
queue<int> zeros;
vector<int> orders;
for (auto p : prerequisites) graph[p.second].insert(p.first);
for (auto v : graph)
for (auto w : v) degrees[w]++;
for (int i = 0; i < numCourses; ++i)
if (degrees[i] == 0) zeros.push(i);
while (!zeros.empty()) {
auto v = zeros.front(); zeros.pop();
orders.push_back(v);
numCourses--;
for (auto w : graph[v])
if (--degrees[w] == 0) zeros.push(w);
}
if (numCourses == 0) return orders;
return {};
}
};
269 Alien Dictionary
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.
For example, Given the following words in dictionary,
[ "wrt", "wrf", "er", "ett", "rftt" ]
The correct order is: "wertf".
Note:
You may assume all letters are in lowercase. If the order is invalid, return an empty string. There may be multiple valid order of letters, return any one of them is fine.
class Solution {
public:
string alienOrder(vector<string>& words) {
if (words.size() == 0) return {};
unordered_map<char, unordered_set<char>> graph;
unordered_map<char, int> degree;
for (auto word : words) for (auto c : word) graph[c], degree[c] = 0;
for (int i = 1; i < words.size(); ++i) {
int len = min(words[i].size(), words[i-1].size());
for (int j = 0; j < len; ++j) {
if (words[i-1][j] != words[i][j]) {
graph[words[i-1][j]].insert(words[i][j]);
break;
}
}
}
string res;
queue<char> q;
for (auto kv : graph) {
for (auto c : kv.second) degree[c]++;
}
for (auto kv : degree)
if (kv.second == 0) q.push(kv.first);
int cnt = graph.size();
while (!q.empty()) {
auto v = q.front(); q.pop();
// res.push_back(v);
res += v;
cnt--;
for (auto w : graph[v]) {
if (--degree[w] == 0) q.push(w);
}
}
if (cnt != 0) return "";
return res;
}
};
332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note: If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. All airports are represented by three capital letters (IATA code). You may assume all tickets form at least one valid itinerary.
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.
DFS solution:
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
vector<string> res;
unordered_map<string, multiset<string>> graph;
for (auto t : tickets) {
graph[t.first].insert(t.second);
}
dfs(graph, "JFK", res);
reverse(res.begin(), res.end());
return res;
}
void dfs(unordered_map<string, multiset<string>>& graph, string v, vector<string>& res) {
while (graph[v].size()) {
auto dest = *graph[v].begin();
graph[v].erase(graph[v].begin());
dfs(graph, dest, res);
}
res.push_back(v);
}
};
BFS solution:
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, multiset<string>> graph;
for (auto ticket : tickets) {
graph[ticket.first].insert(ticket.second);
}
vector<string> res;
stack<string> q;
q.push("JFK");
while (!q.empty()) {
auto from = q.top();
if (graph[from].size() == 0) {
res.push_back(from);
q.pop();
} else {
auto to = graph[from].begin();
q.push(*to);
graph[from].erase(to);
}
}
reverse(res.begin(), res.end());
return res;
}
};