1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public: int shortestPathLength(vector<vector<int>>& graph) { int n = graph.size(); int mask = 1 << n; vector<vector<int>> dist(mask, vector<int>(n + 1, INT_MAX)); deque<vector<int>> d; for (int i = 0; i < n; i ++) { dist[1 << i][i] = 0; d.push_back({1 << i, i}); } while (!d.empty()) { auto poll = d.front(); d.pop_front(); int state = poll[0], u = poll[1], step = dist[state][u]; if (state == mask - 1) return step; for (int i: graph[u]) { if (dist[state | (1 << i)][i] == INT_MAX) { dist[state | (1 << i)][i] = step + 1; d.push_back({state | (1 << i), i}); } } } return -1; } };
|