JavaScript Coding Test Course, Bellman-Ford

Hello. Today, we will delve into the Bellman-Ford algorithm for those of you preparing for JavaScript coding tests. The Bellman-Ford algorithm is one of the algorithms used to find the shortest path in graph theory, with the advantage that it can be applied even when there are edges with negative weights. In this article, we will cover the overview, principles, problem-solving process, and implementation in JavaScript of the Bellman-Ford algorithm.

1. Overview of the Bellman-Ford Algorithm

The Bellman-Ford algorithm is a graph algorithm used to find the shortest path from one vertex to another. This algorithm has the following characteristics:

  • It can be used even if there are edges with negative weights.
  • It can verify if there are cycles in the graph, or if no negative cycles exist.

2. Principles of the Bellman-Ford Algorithm

The Bellman-Ford algorithm operates on the following principles:

  1. Set the starting vertex and initialize the distance value for that vertex to 0. Set the distance values for all other vertices to infinity.
  2. Examine each edge once to update the shortest distance from the starting vertex to the ending vertex of each edge.
  3. Repeat this process V - 1 times (the shortest path in a graph passes through at most V - 1 edges).
  4. Finally, check all edges again. If any distance values are updated, it is concluded that a negative cycle exists.

3. Problem Statement

Let’s solve the following problem:

Problem:
When given n cities and m roads, each road has a weight that represents the distance from the starting city to the destination city.
Generally, the starting city is city 1, and the destination city is city n.
Write a function to find the shortest distance from city 1 to city n. (There may be negative edges.)

4. Problem-Solving Process

Here is a detailed explanation of how to solve this problem using the Bellman-Ford algorithm:

4.1. Input Data Structure Design

We need to define the input data required to solve the problem. First, we need to design a structure that contains the number of cities, the number of roads, and information about each road. Below is an example of how to represent roads using an array of objects:


    // Number of cities and number of roads
    const n = 5; // Number of cities
    const m = 8; // Number of roads

    // Road information (starting city, destination city, distance)
    const roads = [
        { from: 1, to: 2, weight: 4 },
        { from: 1, to: 3, weight: 2 },
        { from: 2, to: 3, weight: 5 },
        { from: 2, to: 4, weight: 10 },
        { from: 3, to: 2, weight: 1 },
        { from: 3, to: 4, weight: 3 },
        { from: 4, to: 5, weight: 3 },
        { from: 2, to: 5, weight: 12 }
    ];
    

4.2. Initialization

Next, we initialize the distance values. The distance for city 1 is set to 0, and the distances for the other cities are set to infinity:


    const INF = Infinity; // Infinite value
    const distance = Array(n + 1).fill(INF); // Distance array from 1 to n
    distance[1] = 0; // Initialize distance for starting city
    

4.3. Implementing the Bellman-Ford Algorithm

Now, let’s implement the Bellman-Ford algorithm. We will update the distance values by iterating through the edges n-1 times:


    for (let i = 1; i < n; i++) {
        for (const road of roads) {
            if (distance[road.from] + road.weight < distance[road.to]) {
                distance[road.to] = distance[road.from] + road.weight;
            }
        }
    }
    

4.4. Checking for Negative Cycles

Finally, we implement a process to check all edges again to see if there are any negative cycles:


    let hasNegativeCycle = false;

    for (const road of roads) {
        if (distance[road.from] + road.weight < distance[road.to]) {
            hasNegativeCycle = true; // Negative cycle exists
            break;
        }
    }

    if (hasNegativeCycle) {
        console.log("A negative cycle exists.");
    } else {
        console.log("Shortest distance:", distance[n]);
    }
    

5. Complete Code

Putting all the above processes together, we will create a complete JavaScript code:


    function bellmanFord(n, roads) {
        const INF = Infinity;
        const distance = Array(n + 1).fill(INF);
        distance[1] = 0;

        // Bellman-Ford algorithm
        for (let i = 1; i < n; i++) {
            for (const road of roads) {
                if (distance[road.from] + road.weight < distance[road.to]) {
                    distance[road.to] = distance[road.from] + road.weight;
                }
            }
        }

        // Check for negative cycles
        let hasNegativeCycle = false;
        for (const road of roads) {
            if (distance[road.from] + road.weight < distance[road.to]) {
                hasNegativeCycle = true;
                break;
            }
        }

        if (hasNegativeCycle) {
            console.log("A negative cycle exists.");
        } else {
            console.log("Shortest distance:", distance[n]);
        }
    }

    // Example usage
    const n = 5;
    const roads = [
        { from: 1, to: 2, weight: 4 },
        { from: 1, to: 3, weight: 2 },
        { from: 2, to: 3, weight: 5 },
        { from: 2, to: 4, weight: 10 },
        { from: 3, to: 2, weight: 1 },
        { from: 3, to: 4, weight: 3 },
        { from: 4, to: 5, weight: 3 },
        { from: 2, to: 5, weight: 12 }
    ];

    bellmanFord(n, roads);
    

6. Conclusion

In this article, we thoroughly explored the basic concepts and principles of the Bellman-Ford algorithm, as well as the process of solving problems using it. This algorithm is useful when there are edges with negative weights and is one of the important algorithms to learn in graph theory. Since it is a frequently tested topic in coding tests, be sure to understand it well.

I hope you continue to build your skills through various algorithms and problem-solving, and feel free to leave any questions in the comments. Thank you!