transitive_closure.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package generator
  14. import "sort"
  15. type edge struct {
  16. from string
  17. to string
  18. }
  19. func transitiveClosure(in map[string][]string) map[string][]string {
  20. adj := make(map[edge]bool)
  21. imports := make(map[string]struct{})
  22. for from, tos := range in {
  23. for _, to := range tos {
  24. adj[edge{from, to}] = true
  25. imports[to] = struct{}{}
  26. }
  27. }
  28. // Warshal's algorithm
  29. for k := range in {
  30. for i := range in {
  31. if !adj[edge{i, k}] {
  32. continue
  33. }
  34. for j := range imports {
  35. if adj[edge{i, j}] {
  36. continue
  37. }
  38. if adj[edge{k, j}] {
  39. adj[edge{i, j}] = true
  40. }
  41. }
  42. }
  43. }
  44. out := make(map[string][]string, len(in))
  45. for i := range in {
  46. for j := range imports {
  47. if adj[edge{i, j}] {
  48. out[i] = append(out[i], j)
  49. }
  50. }
  51. sort.Strings(out[i])
  52. }
  53. return out
  54. }