😕题目描述
😔分析

比如对0开始进行查找,就需要从0开始,按照逆序进行查找,所有可以到达区域的最小值。但是这样会有很多冗余查询,比如查询了0之后,再查询1,就会冗余很大一部分。
所以需要多每个已经查询的结果进行缓存,比如
- 在查询0的时候,得到的结果是5,则将0-5以kv方式缓存下来;
然后进行递归缓存,最后在1查询的时候,就可以直接得到5的结果。
😏答案
func BFS3(graph [][]int, quite []int, t int, cache map[int]int) int {// 缓存查询,确认之前是否已经查询过if v, ok := cache[t]; ok {return v}index := tfor i, _ := range graph {if graph[i][t] == 1 {if quite[index] > quite[i] {index = i}temp := BFS3(graph, quite, i, cache)if quite[index] > quite[temp] {index = temp}}}// 缓存更新,将最新的查询结果缓存cache[t] = indexreturn index}func loudAndRich(richer [][]int, quiet []int) []int {graph := make([][]int, len(quiet))cache := make(map[int]int)for i, _ := range graph {graph[i] = make([]int, len(quiet))}for _, v := range richer {graph[v[0]][v[1]] = 1}res := make([]int, len(quiet))for i, _ := range res {res[i] = BFS3(graph, quiet, i, cache)}return res}
