FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode-algorithms/src/ReconstructItinerary.java at master · anishLearnsToCode/leetcode-algorithms · GitHub
anishLearnsToCode
/
leetcode-algorithms
Public
Notifications
You must be signed in to change notification settings
Fork
17
Star
98
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode-algorithms
/
src
/
ReconstructItinerary.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
40 lines (36 loc) · 1.4 KB
Breadcrumbs
leetcode-algorithms
/
src
/
ReconstructItinerary.java
Copy path
File metadata and controls
40 lines (36 loc) · 1.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// https://leetcode.com/problems/reconstruct-itinerary
// E = |flights|, V = |airports| N = E / V
// T: O(V * NlogN) = O(E log(E / V))
// S: O(V + E)
import
java
.
util
.
ArrayList
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
List
;
import
java
.
util
.
Map
;
import
java
.
util
.
PriorityQueue
;
import
java
.
util
.
Queue
;
public
class
ReconstructItinerary
{
public
List
<
String
>
findItinerary
(
List
<
List
<
String
>>
tickets
) {
final
Map
<
String
,
Queue
<
String
>>
graph
=
createGraph
(
tickets
);
final
List
<
String
>
result
=
new
ArrayList
<>();
dfs
(
graph
,
"JFK"
,
result
);
return
result
.
reversed
();
}
private
static
void
dfs
(
Map
<
String
,
Queue
<
String
>>
graph
,
String
current
,
List
<
String
>
result
) {
final
Queue
<
String
>
queue
=
graph
.
getOrDefault
(
current
,
new
PriorityQueue
<>());
while
(!
queue
.
isEmpty
()) {
final
String
to
=
queue
.
poll
();
dfs
(
graph
,
to
,
result
);
}
result
.
add
(
current
);
}
private
static
Map
<
String
,
Queue
<
String
>>
createGraph
(
List
<
List
<
String
>>
tickets
) {
final
Map
<
String
,
Queue
<
String
>>
graph
=
new
HashMap
<>();
for
(
List
<
String
>
ticket
:
tickets
) {
final
String
from
=
ticket
.
get
(
0
),
to
=
ticket
.
get
(
1
);
final
Queue
<
String
>
queue
=
graph
.
getOrDefault
(
from
,
new
PriorityQueue
<>());
queue
.
add
(
to
);
graph
.
putIfAbsent
(
from
,
queue
);
}
return
graph
;
}
}
Back
|
FazBrowse Home
|
New Git URL