Skip to content

Instantly share code, notes, and snippets.

@fpdjsns
Created June 3, 2018 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpdjsns/ee6b67d1b11c5c199bf0807826377a50 to your computer and use it in GitHub Desktop.
Save fpdjsns/ee6b67d1b11c5c199bf0807826377a50 to your computer and use it in GitHub Desktop.
[leetcode] 847. Shortest Path Visiting All Nodes : https://leetcode.com/problems/shortest-path-visiting-all-nodes/description/
class Solution {
public:
int MAX = 100;
int len = 0;
vector<vector<int>> d = vector<vector<int>>();
vector<vector<int>> adj = vector<vector<int>>();
int TSP(int now, int visit) {
visit |= (1 << now);
if (visit == (1 << len) - 1)
return 0;
int& ret = d[visit][now];
//memorization
if (ret > 0)
return ret;
ret = 100;
for (int i = 0; i<adj[now].size(); i++) {
int next = adj[now][i];
ret = min(ret, TSP(next, visit) + 1);
}
return ret;
}
int shortestPathLength(vector<vector<int>>& graph) {
//initialize
len = graph.size();
adj = graph;
//solve -> with DP
int ans = 100;
for (int i = 0; i < len; i++) {
d.clear();
d.resize(1 << len, vector<int>(len, -1));
ans = min(TSP(i, 0), ans);
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment