-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathB.cpp
executable file
·65 lines (56 loc) · 1.28 KB
/
B.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
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <functional>
#include <algorithm>
using namespace std;
string stable_wall(int R, int C, vector<string>& grid) {
string order;
bool cycle = false;
unordered_set<char> letters;
unordered_map<char, int> visited;
unordered_map<char, unordered_set<char>> adj;
// helper function
function<void(char)> dfs = [&](char s) {
visited[s] = 1;
for (auto& u: adj[s]) {
if (visited[u] == 1)
cycle = true;
else if (!visited[u])
dfs(u);
}
visited[s] = 2;
order += s;
};
// initialize
for (int j = 0; j < C; j++)
letters.insert(grid[R - 1][j]);
// create adjacency list
for (int i = R - 2; i >= 0; i--)
for (int j = 0; j < C; j++) {
if (grid[i][j] != grid[i + 1][j])
adj[grid[i + 1][j]].insert(grid[i][j]);
letters.insert(grid[i][j]);
}
// topological sort
for (auto& letter: letters)
if (!visited[letter])
dfs(letter);
reverse(order.begin(), order.end());
return cycle ? "-1" : order;
}
int main() {
int T;
cin >> T;
for (int x = 1; x <= T; x++) {
int R, C;
cin >> R >> C;
vector<string> grid(R);
for (int i = 0; i < R; i++)
cin >> grid[i];
cout << "Case #" << x << ": " << stable_wall(R, C, grid) << endl;
}
return 0;
}