Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
shortest-path-visiting-all-nodes.cpp 985 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-06-03 13:41 +08:00 . Create shortest-path-visiting-all-nodes.cpp
// 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());
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助