|
| 1 | +class Solution { |
| 2 | + |
| 3 | + // Solution by Sergey Leschev |
| 4 | + // 2959. Number of Possible Sets of Closing Branches |
| 5 | + |
| 6 | + // Time complexity: O(2^n . N^3) |
| 7 | + // Space complexity: O(N^2) |
| 8 | + |
| 9 | + func numberOfSets(_ n: Int, _ maxDistance: Int, _ roads: [[Int]]) -> Int { |
| 10 | + var ans = 0 |
| 11 | + |
| 12 | + // Iterate through all subsets of nodes (1 << n) using bitmasking |
| 13 | + for i in 0..<(1 << n) { |
| 14 | + // Create an adjacency matrix to represent the graph |
| 15 | + var g = [[Int]](repeating: [Int](repeating: 1_000_000_000, count: n), count: n) |
| 16 | + |
| 17 | + // Update the graph based on the selected nodes in the subset |
| 18 | + for it in roads { |
| 19 | + let x = it[0] |
| 20 | + let y = it[1] |
| 21 | + let w = it[2] |
| 22 | + if (i >> x & 1) == 1 && (i >> y & 1) == 1 { |
| 23 | + g[x][y] = min(g[x][y], w) |
| 24 | + g[y][x] = min(g[y][x], w) |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // Set diagonal elements to 0 |
| 29 | + for j in 0..<n { |
| 30 | + g[j][j] = 0 |
| 31 | + } |
| 32 | + |
| 33 | + // Floyd-Warshall algorithm for finding the shortest paths |
| 34 | + for p in 0..<n { |
| 35 | + for q in 0..<n { |
| 36 | + for k in 0..<n { |
| 37 | + g[q][k] = min(g[q][k], g[q][p] + g[p][k]) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Check if the selected nodes in the subset form a valid set |
| 43 | + var ok = 1 |
| 44 | + for j in 0..<n { |
| 45 | + for k in 0..<n { |
| 46 | + if (i >> j & 1) == 1 && (i >> k & 1) == 1 { |
| 47 | + ok &= (g[j][k] <= maxDistance ? 1 : 0) |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Increment the answer if the subset forms a valid set |
| 53 | + ans += ok |
| 54 | + } |
| 55 | + return ans |
| 56 | + } |
| 57 | +} |
0 commit comments