|
| 1 | +package graph |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | +) |
| 6 | + |
| 7 | +func TestKahn(t *testing.T) { |
| 8 | + testCases := []struct { |
| 9 | + name string |
| 10 | + n int |
| 11 | + dependencies [][]int |
| 12 | + wantNil bool |
| 13 | + }{ |
| 14 | + { |
| 15 | + "linear graph", |
| 16 | + 3, |
| 17 | + [][]int{{0, 1}, {1, 2}}, |
| 18 | + false, |
| 19 | + }, |
| 20 | + { |
| 21 | + "diamond graph", |
| 22 | + 4, |
| 23 | + [][]int{{0, 1}, {0, 2}, {1, 3}, {2, 3}}, |
| 24 | + false, |
| 25 | + }, |
| 26 | + { |
| 27 | + "star graph", |
| 28 | + 5, |
| 29 | + [][]int{{0, 1}, {0, 2}, {0, 3}, {0, 4}}, |
| 30 | + false, |
| 31 | + }, |
| 32 | + { |
| 33 | + "disconnected graph", |
| 34 | + 5, |
| 35 | + [][]int{{0, 1}, {0, 2}, {3, 4}}, |
| 36 | + false, |
| 37 | + }, |
| 38 | + { |
| 39 | + "cycle graph 1", |
| 40 | + 4, |
| 41 | + [][]int{{0, 1}, {1, 2}, {2, 3}, {3, 0}}, |
| 42 | + true, |
| 43 | + }, |
| 44 | + { |
| 45 | + "cycle graph 2", |
| 46 | + 4, |
| 47 | + [][]int{{0, 1}, {1, 2}, {2, 0}, {2, 3}}, |
| 48 | + true, |
| 49 | + }, |
| 50 | + { |
| 51 | + "single node graph", |
| 52 | + 1, |
| 53 | + [][]int{}, |
| 54 | + false, |
| 55 | + }, |
| 56 | + { |
| 57 | + "empty graph", |
| 58 | + 0, |
| 59 | + [][]int{}, |
| 60 | + false, |
| 61 | + }, |
| 62 | + { |
| 63 | + "redundant dependencies", |
| 64 | + 4, |
| 65 | + [][]int{{0, 1}, {1, 2}, {1, 2}, {2, 3}}, |
| 66 | + false, |
| 67 | + }, |
| 68 | + { |
| 69 | + "island vertex", |
| 70 | + 4, |
| 71 | + [][]int{{0, 1}, {0, 2}}, |
| 72 | + false, |
| 73 | + }, |
| 74 | + { |
| 75 | + "more complicated graph", |
| 76 | + 14, |
| 77 | + [][]int{{1, 9}, {2, 0}, {3, 2}, {4, 5}, {4, 6}, {4, 7}, {6, 7}, |
| 78 | + {7, 8}, {9, 4}, {10, 0}, {10, 1}, {10, 12}, {11, 13}, |
| 79 | + {12, 0}, {12, 11}, {13, 5}}, |
| 80 | + false, |
| 81 | + }, |
| 82 | + } |
| 83 | + |
| 84 | + for _, tc := range testCases { |
| 85 | + t.Run(tc.name, func(t *testing.T) { |
| 86 | + actual := Kahn(tc.n, tc.dependencies) |
| 87 | + if tc.wantNil { |
| 88 | + if actual != nil { |
| 89 | + t.Errorf("Kahn(%d, %v) = %v; want nil", tc.n, tc.dependencies, actual) |
| 90 | + } |
| 91 | + } else { |
| 92 | + if actual == nil { |
| 93 | + t.Errorf("Kahn(%d, %v) = nil; want valid order", tc.n, tc.dependencies) |
| 94 | + } else { |
| 95 | + seen := make([]bool, tc.n) |
| 96 | + positions := make([]int, tc.n) |
| 97 | + for i, v := range actual { |
| 98 | + seen[v] = true |
| 99 | + positions[v] = i |
| 100 | + } |
| 101 | + for i, v := range seen { |
| 102 | + if !v { |
| 103 | + t.Errorf("missing vertex %v", i) |
| 104 | + } |
| 105 | + } |
| 106 | + for _, d := range tc.dependencies { |
| 107 | + if positions[d[0]] > positions[d[1]] { |
| 108 | + t.Errorf("dependency %v not satisfied", d) |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + }) |
| 114 | + } |
| 115 | +} |
0 commit comments