-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths0332_reconstruct_itinerary.rs
70 lines (61 loc) · 2.02 KB
/
s0332_reconstruct_itinerary.rs
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
#![allow(unused)]
pub struct Solution {}
impl Solution {
pub fn find_itinerary(tickets: Vec<Vec<String>>) -> Vec<String> {
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap};
let mut graph: HashMap<&str, BinaryHeap<Reverse<&str>>> = HashMap::new();
for ticket in tickets.iter() {
graph.entry(&ticket[0]).or_insert_with(BinaryHeap::new).push(Reverse(&ticket[1]));
}
let mut ans: Vec<String> = Vec::with_capacity(tickets.len()+1);
let mut stack: Vec<&str> = vec!["JFK"];
while let Some(src) = stack.last() {
if let Some(dsts) = graph.get_mut(src) {
if !dsts.is_empty() {
if let Some(dst) = dsts.pop() {
stack.push(dst.0);
}
continue;
}
}
if let Some(last) = stack.pop() {
ans.push(last.to_string());
}
}
ans.reverse();
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_218() {
assert_eq!(
Solution::find_itinerary(vec![
vec!["MUC".to_string(), "LHR".to_string()],
vec!["JFK".to_string(), "MUC".to_string()],
vec!["SFO".to_string(), "SJC".to_string()],
vec!["LHR".to_string(), "SFO".to_string()],
]),
vec![
"JFK".to_string(), "MUC".to_string(), "LHR".to_string(),
"SFO".to_string(), "SJC".to_string()
]
);
assert_eq!(
Solution::find_itinerary(vec![
vec!["JFK".to_string(), "SFO".to_string()],
vec!["JFK".to_string(), "ATL".to_string()],
vec!["SFO".to_string(), "ATL".to_string()],
vec!["ATL".to_string(), "JFK".to_string()],
vec!["ATL".to_string(), "SFO".to_string()],
]),
vec![
"JFK".to_string(), "ATL".to_string(), "JFK".to_string(),
"SFO".to_string(), "ATL".to_string(), "SFO".to_string()
]
);
}
}