How do I extend this bellman-ford, so I can limit the number of edge-traversals (k), that are permitted?

And no, it's not just a matter of limiting the outer loop to run k times, since BF updates every edge, when running the inner loop.

int[] distance = new int[nodeCount];
Arrays.fill(distance, Integer.MAX_VALUE);
distance[sourceNode] = 0;

int u, v, w;

for (int i = 1; i <= nodeCount-1; i++) {
    for (int j = 0; j < edges.length; j++) {

        u = edges[j].from;  v = edges[j].to;  w = edges[j].weight;

        if (distance[v] > distance[u] + w) {
            distance[v] = distance[u] + w;
return distance[targetNode];

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.