-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAlien dictionary.cpp
77 lines (65 loc) · 1.7 KB
/
Alien dictionary.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Graph{
private:
int n;
vector<int> *arr;
int *indegree;
bool _topoUtil(bool visited[], vector<int> &res);
public:
Graph(int n);
void addEdge(int u, int v);
string topoSort();
};
Graph::Graph(int n){
this->n = n;
arr = new vector<int>[n];
indegree = new int[n];
for(int i = 0; i < n; i++)
indegree[i] = 0;
}
void Graph::addEdge(int u, int v){
arr[u].push_back(v);
indegree[v]++;
}
string Graph::topoSort(){
bool visited[n];
vector<int> res;
string ans;
memset(visited, false, sizeof(visited));
_topoUtil(visited, res);
for(int i = 0; i < n; i++){
ans = ans + (char)(res[i] + 97);
}
return ans;
}
bool Graph::_topoUtil(bool visited[], vector<int> &res){
if(res.size() == n)
return true;
for(int i = 0; i < n; i++){
if(indegree[i] == 0 && visited[i] == false){
visited[i] = true;
for(int j = 0; j < arr[i].size(); j++)
indegree[arr[i][j]]--;
res.push_back(i);
if(_topoUtil(visited, res))
return true;
visited[i] = false;
for(int j = 0; j < arr[i].size(); j++)
indegree[arr[i][j]]--;
res.pop_back();
}
}
return false;
}
string printOrder(string dict[], int n, int k) {
Graph g(k);
for(int i = 0; i < n - 1; i++){
string word1 = dict[i], word2 = dict[i + 1];
for(int j = 0; j < word1.length() && j < word2.length(); j++){
if(word1[j] != word2[j]){
g.addEdge(word1[j] - 97, word2[j] - 97);
break;
}
}
}
return g.topoSort();
}