Graphs
Graphs
6 Bellman-Ford algorithm
Dynamic programming:
Compute the optimal solution from [a][b] via c ⇒ [c][a][b], we’ll already have computed the optimal
solution from [a][c] and [c][b]
for (int i = 0; i < n; ++i)
adj[i][i] = 0;
for (int k = 0; k < n; ++k)
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
adj[i][j] = min(adj[i][j], adj[i][k] + adj[k][j]);
while(!q.empty()){
int level = q.size();
vector<int> v;
//now start traversing within level
for (int i=0; i<level;i++){
//Grab, pop, push, add
TreeNode* grab = q.front();
q.pop();
if (grab->left){q.push(grab->left);}
if (grab->right){q.push(grab->right);}
v.push_back(grab->val);
}
ans.push_back(v);
}
return ans;
}