Skip to content

Instantly share code, notes, and snippets.

@fwang49asu
Created March 10, 2019 02:20
Show Gist options
  • Save fwang49asu/fcd55ab486fffd23afa410861731eb51 to your computer and use it in GitHub Desktop.
Save fwang49asu/fcd55ab486fffd23afa410861731eb51 to your computer and use it in GitHub Desktop.
Leetcode 269 BFS
class Solution {
private:
string compare(string& a, string& b) {
int n = min(a.length(), b.length());
for (int i = 0; i < n; ++i) {
if (a[i] != b[i]) {
return {a[i], b[i]};
}
}
return "";
}
public:
string alienOrder(vector<string>& words) {
unordered_map<char, int> indegrees;
for (string& str : words) {
for (char c : str) {
indegrees[c] = 0;
}
}
int targetSize = indegrees.size();
vector<unordered_set<char>> graph(256);
for (int i = 1; i < words.size(); ++i) {
string diff = compare(words[i - 1], words[i]);
if (diff == "") {
continue;
}
if (graph[diff[0]].find(diff[1]) == graph[diff[0]].end()) {
indegrees[diff[1]]++;
graph[diff[0]].insert(diff[1]);
}
}
queue<char> q;
for (auto p : indegrees) {
if (p.second == 0) {
q.push(p.first);
}
}
string result = "";
while (!q.empty()) {
char front = q.front();
result += front;
q.pop();
auto& nextset = graph[front];
for (char next : nextset) {
indegrees[next]--;
if (indegrees[next] == 0) {
q.push(next);
}
}
}
return result.length() == targetSize ? result : "";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment