forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathshortest-path-visiting-all-nodes.cpp
More file actions
29 lines (28 loc) · 985 Bytes
/
shortest-path-visiting-all-nodes.cpp
File metadata and controls
29 lines (28 loc) · 985 Bytes
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
27
28
29
// Time: O(n * 2^n)
// Space: O(n * 2^n)
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
static const auto& INF = numeric_limits<int>::max();
vector<vector<int>> dp(1 << graph.size(),
vector<int>(graph.size(), INF));
queue<pair<int, int>> q;
for (int i = 0; i < graph.size(); ++i) {
dp[1 << i][i] = 0;
q.emplace(1 << i, i);
}
while (!q.empty()) {
int state, node;
tie(state, node) = q.front(); q.pop();
auto steps = dp[state][node];
for (const auto& nei : graph[node]) {
auto new_state = state | (1 << nei);
if (dp[new_state][nei] == INF) {
dp[new_state][nei] = steps + 1;
q.emplace(new_state, nei);
}
}
}
return *min_element(dp.back().cbegin(), dp.back().cend());
}
};