Skip to content

Commit 7e18c10

Browse files
authored
Merge pull request #1935 from kkr2/feat/0332-reconstruct-itenerary.go
Create 0332-reconstruct-itenerary.go
2 parents 13cf381 + 4edd518 commit 7e18c10

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Diff for: go/0332-reconstruct-itenerary.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
func findItinerary(tickets [][]string) []string {
2+
3+
adjMap := make(map[string][]string)
4+
5+
for i := 0; i < len(tickets); i++ {
6+
adjMap[tickets[i][0]] = append(adjMap[tickets[i][0]], tickets[i][1])
7+
}
8+
9+
for i := 0; i < len(tickets); i++ {
10+
sort.Strings(adjMap[tickets[i][0]])
11+
}
12+
13+
res := []string{"JFK"}
14+
15+
var dfs func(source string) bool
16+
17+
dfs = func(src string) bool {
18+
19+
if len(res) == len(tickets)+1 {
20+
return true
21+
}
22+
23+
if _, ok := adjMap[src]; !ok {
24+
return false
25+
}
26+
27+
destinationList := adjMap[src]
28+
29+
for i, destination := range destinationList {
30+
31+
adjMap[src] = append(adjMap[src][:i], adjMap[src][i+1:]...)
32+
33+
res = append(res, destination)
34+
if dfs(destination) == true {
35+
return true
36+
}
37+
adjMap[src] = append(adjMap[src][:i+1], adjMap[src][i:]...)
38+
adjMap[src][i] = destination
39+
40+
res = res[:len(res)-1]
41+
}
42+
43+
return false
44+
}
45+
46+
dfs("JFK")
47+
return res
48+
}

0 commit comments

Comments
 (0)