Skip to content

Instantly share code, notes, and snippets.

@z11i
Last active November 11, 2015 03:02
Show Gist options
  • Select an option

  • Save z11i/c59b016dba979e7a2305 to your computer and use it in GitHub Desktop.

Select an option

Save z11i/c59b016dba979e7a2305 to your computer and use it in GitHub Desktop.
memo = new int[V][1 << V];
T = new int[V][V]; // adjacency matrix
int min_dist_from_0 = DP_TSP(0, 1);
int DP_TSP(int u, int m) { // m is visited mask (bitmask)
if (m == ((1 << V) - 1)) // all 1, all vertices have been visited
return T[u][0]; // no choice, return to vertex 0
if (memo[u][m] != -1) // computed before
return memo[u][m];
memo[u][m] = INF; // general case
for (int v = 0; v < V; v++) { // for each v in V
if ((m & (1 << v)) == 0) { // if v is not turned on
memo[u][m] = Math.min(memo[u][m],
T[u][v] + DP_TSP(v, m | (1 << v))); // weight[u][v] + DP_TSP(v, m with v-th bit turned on)
}
}
return memo[u][m];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment