Skip to content

Commit 7e1ad0e

Browse files
authored
Merge pull request #3005 from mdmzfzl/main
Create: 0332-reconstruct-itinerary.rs
2 parents 9f43422 + 474f9a4 commit 7e1ad0e

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: rust/0332-reconstruct-itinerary.rs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use std::cmp::Reverse;
2+
use std::collections::{BinaryHeap, HashMap};
3+
4+
impl Solution {
5+
pub fn find_itinerary(tickets: Vec<Vec<String>>) -> Vec<String> {
6+
let mut graph: HashMap<&str, BinaryHeap<Reverse<&str>>> = HashMap::new();
7+
for ticket in tickets.iter() {
8+
graph
9+
.entry(&ticket[0])
10+
.or_insert_with(BinaryHeap::new)
11+
.push(Reverse(&ticket[1]));
12+
}
13+
let mut answer: Vec<String> = Vec::with_capacity(tickets.len() + 1);
14+
let mut stack: Vec<&str> = vec!["JFK"];
15+
while let Some(src) = stack.last() {
16+
if let Some(dsts) = graph.get_mut(src) {
17+
if !dsts.is_empty() {
18+
if let Some(dst) = dsts.pop() {
19+
stack.push(dst.0);
20+
}
21+
continue;
22+
}
23+
}
24+
if let Some(last) = stack.pop() {
25+
answer.push(last.to_string());
26+
}
27+
}
28+
answer.reverse();
29+
answer
30+
}
31+
}

0 commit comments

Comments
 (0)