forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
90 lines (73 loc) · 2.81 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/// Source : https://leetcode.com/problems/shortest-path-with-alternating-colors/
/// Author : liuyubobobo
/// Time : 2019-07-20
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;
/// BFS
/// Time Complexity: O(V + E)
/// Space Complexity: O(V + E)
class Solution {
public:
vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& red_edges, vector<vector<int>>& blue_edges) {
vector<unordered_map<int, unordered_set<int>>> g(n);
for(vector<int>& edge: red_edges)
g[edge[0]][edge[1]].insert(1);
for(vector<int>& edge: blue_edges)
g[edge[0]][edge[1]].insert(2);
queue<pair<int, int>> q;
unordered_set<int> visited;
vector<int> res(n, -1);
res[0] = 0;
for(const pair<int, unordered_set<int>>& p: g[0])
if(p.first)
for(int color: p.second){
res[p.first] = 1;
q.push(make_pair(p.first * 10 + color, 1));
visited.insert(p.first * 10 + color);
}
while(!q.empty()){
int cur = q.front().first / 10;
int color = q.front().first % 10;
int step = q.front().second;
q.pop();
for(const pair<int, unordered_set<int>>& p: g[cur]){
for(int newcolor: p.second){
int hash = p.first * 10 + newcolor;
if(!visited.count(hash) && newcolor != color){
q.push(make_pair(hash, step + 1));
if(res[p.first] == -1)
res[p.first] = step + 1;
visited.insert(hash);
}
}
}
}
return res;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec) cout << e << " "; cout << endl;
}
int main() {
vector<vector<int> > red_edges1 = {{0, 1}, {0, 2}};
vector<vector<int> > blue_edges1 = {{1, 0}};
print_vec(Solution().shortestAlternatingPaths(3, red_edges1, blue_edges1));
// 0 1 1
vector<vector<int> > red_edges2 = {{0, 1}};
vector<vector<int> > blue_edges2 = {{1, 2}};
print_vec(Solution().shortestAlternatingPaths(3, red_edges2, blue_edges2));
// 0 1 2
vector<vector<int> > red_edges3 = {{0, 1}, {1, 2}, {2, 3}, {3, 4}};
vector<vector<int> > blue_edges3 = {{1, 2}, {2, 3}, {3, 1}};
print_vec(Solution().shortestAlternatingPaths(5, red_edges3, blue_edges3));
// 0 1 2 3 7
vector<vector<int> > red_edges4 = {{2, 2}, {0, 1}, {0, 3}, {0, 0}, {0, 4}, {2, 1}, {2, 0}, {1, 4}, {3, 4}};
vector<vector<int> > blue_edges4 = {{1, 3}, {0, 0}, {0, 3}, {4, 2}, {1, 0}};
print_vec(Solution().shortestAlternatingPaths(5, red_edges4, blue_edges4));
// 0 1 2 1 1
return 0;
}