Merge pull request #1182 from zzz607/master

添加 0332.重新安排行程 Go版本
This commit is contained in:
程序员Carl
2022-04-13 09:49:10 +08:00
committed by GitHub

View File

@ -626,5 +626,77 @@ for line in tickets {
} }
``` ```
### Go
```Go
// 先排序,然后找到第一条路径即可返回
func findItinerary(tickets [][]string) []string {
var path []string // 用来保存搜索的路径
data := make(map[string]ticketSlice) // 用来保存tickets排序后的结果
var search func(airport string) bool
search = func(airport string) bool {
if len(path) == len(tickets) {
path = append(path, airport)
return true
}
to := data[airport]
for _, item := range to {
if item.Count == 0 {
// 已用完
continue
}
path = append(path, airport)
item.Count--
if search(item.To) { return true }
item.Count++
path = path[:len(path) - 1]
}
return false
}
// 排序
// 感觉这段代码有点啰嗦,不知道能不能简化一下
tmp := make(map[string]map[string]int)
for _, ticket := range tickets {
if to, ok := tmp[ticket[0]]; ok {
if _, ok2 := to[ticket[1]]; ok2 {
to[ticket[1]]++
} else {
to[ticket[1]] = 1
}
} else {
tmp[ticket[0]] = map[string]int{
ticket[1]: 1,
}
}
}
for from, to := range tmp {
var tmp ticketSlice
for to, num := range to {
tmp = append(tmp, &ticketStat{To: to, Count: num})
}
sort.Sort(tmp)
data[from] = tmp
}
search("JFK")
return path
}
type ticketStat struct {
To string
Count int
}
type ticketSlice []*ticketStat
func (p ticketSlice) Len() int { return len(p) }
func (p ticketSlice) Less(i, j int) bool { return strings.Compare(p[i].To, p[j].To) == -1 }
func (p ticketSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
```
----------------------- -----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div> <div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>