Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1935 from kkr2/feat/0332-reconstruct-i…
Browse files Browse the repository at this point in the history
…tenerary.go

Create 0332-reconstruct-itenerary.go
  • Loading branch information
tahsintunan authored Jan 8, 2023
2 parents 13cf381 + 4edd518 commit 7e18c10
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions go/0332-reconstruct-itenerary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
func findItinerary(tickets [][]string) []string {

adjMap := make(map[string][]string)

for i := 0; i < len(tickets); i++ {
adjMap[tickets[i][0]] = append(adjMap[tickets[i][0]], tickets[i][1])
}

for i := 0; i < len(tickets); i++ {
sort.Strings(adjMap[tickets[i][0]])
}

res := []string{"JFK"}

var dfs func(source string) bool

dfs = func(src string) bool {

if len(res) == len(tickets)+1 {
return true
}

if _, ok := adjMap[src]; !ok {
return false
}

destinationList := adjMap[src]

for i, destination := range destinationList {

adjMap[src] = append(adjMap[src][:i], adjMap[src][i+1:]...)

res = append(res, destination)
if dfs(destination) == true {
return true
}
adjMap[src] = append(adjMap[src][:i+1], adjMap[src][i:]...)
adjMap[src][i] = destination

res = res[:len(res)-1]
}

return false
}

dfs("JFK")
return res
}

0 comments on commit 7e18c10

Please sign in to comment.