Debian Codegraph @

generator/transitive_closure.go

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