😕题目描述

😔分析

851 喧闹和富有 - 图1
比如对0开始进行查找,就需要从0开始,按照逆序进行查找,所有可以到达区域的最小值。但是这样会有很多冗余查询,比如查询了0之后,再查询1,就会冗余很大一部分。
所以需要多每个已经查询的结果进行缓存,比如

  • 在查询0的时候,得到的结果是5,则将0-5以kv方式缓存下来;

然后进行递归缓存,最后在1查询的时候,就可以直接得到5的结果。

😏答案

  1. func BFS3(graph [][]int, quite []int, t int, cache map[int]int) int {
  2. // 缓存查询,确认之前是否已经查询过
  3. if v, ok := cache[t]; ok {
  4. return v
  5. }
  6. index := t
  7. for i, _ := range graph {
  8. if graph[i][t] == 1 {
  9. if quite[index] > quite[i] {
  10. index = i
  11. }
  12. temp := BFS3(graph, quite, i, cache)
  13. if quite[index] > quite[temp] {
  14. index = temp
  15. }
  16. }
  17. }
  18. // 缓存更新,将最新的查询结果缓存
  19. cache[t] = index
  20. return index
  21. }
  22. func loudAndRich(richer [][]int, quiet []int) []int {
  23. graph := make([][]int, len(quiet))
  24. cache := make(map[int]int)
  25. for i, _ := range graph {
  26. graph[i] = make([]int, len(quiet))
  27. }
  28. for _, v := range richer {
  29. graph[v[0]][v[1]] = 1
  30. }
  31. res := make([]int, len(quiet))
  32. for i, _ := range res {
  33. res[i] = BFS3(graph, quiet, i, cache)
  34. }
  35. return res
  36. }