Home >Backend Development >PHP Tutorial >PHP algorithm design tips: How to use the Bellman-Ford algorithm to solve the single-source shortest path problem?

PHP algorithm design tips: How to use the Bellman-Ford algorithm to solve the single-source shortest path problem?

PHPz
PHPzOriginal
2023-09-19 11:30:14686browse

PHP algorithm design tips: How to use the Bellman-Ford algorithm to solve the single-source shortest path problem?

PHP algorithm design tips: How to use the Bellman-Ford algorithm to solve the single-source shortest path problem?

Overview:
The Bellman-Ford algorithm is a classic algorithm for solving the single-source shortest path problem in graphs. It can handle graphs with negative weight edges and is able to detect the presence of negative weight cycles. This article will introduce how to implement the Bellman-Ford algorithm using PHP and provide code examples.

Background knowledge:
Before we understand the Bellman-Ford algorithm in depth, we need to understand some basic graph theory knowledge.

  1. Representation of graph:
    The graph consists of nodes (vertex) and edges (edge). Nodes can be represented as numbers or strings, and edges can be represented as tuples containing two nodes and weight information.
  2. Graph representation method:
    Adjacency matrix and adjacency list are two common graph representation methods.
  3. Adjacency matrix: Use a two-dimensional array to represent the connection relationship between nodes. If there is an edge between node i and node j, the value in row i and column j in the adjacency matrix is ​​the weight of the edge; if there is no edge, the value at this position is infinity (inf).
  4. Adjacency list: For each node, use a linked list to store information about the edges connected to it.
  5. Single source shortest path problem:
    Given a directed graph, find the shortest path from one source node to all other nodes.

Bellman-Ford algorithm implementation:
The following is a sample code to implement the Bellman-Ford algorithm using PHP:

<?php

class Graph {
    private $vertices;
    private $edges;

    public function __construct($vertices) {
        $this->vertices = $vertices;
        $this->edges = [];
    }

    public function addEdge($start, $end, $weight) {
        $this->edges[] = [$start, $end, $weight];
    }

    public function bellmanFord($source) {
        $distance = [];
        $predecessor = [];

        // 设置源节点到其他所有节点的初始距离为无穷大
        foreach ($this->vertices as $vertex) {
            $distance[$vertex] = INF;
            $predecessor[$vertex] = null;
        }

        $distance[$source] = 0;

        // 对每个节点进行松弛操作
        for ($i = 0; $i < count($this->vertices) - 1; $i++) {
            foreach ($this->edges as $edge) {
                $u = $edge[0];
                $v = $edge[1];
                $w = $edge[2];

                if ($distance[$u] != INF && $distance[$u] + $w < $distance[$v]) {
                    $distance[$v] = $distance[$u] + $w;
                    $predecessor[$v] = $u;
                }
            }
        }

        // 检测负权环
        foreach ($this->edges as $edge) {
            $u = $edge[0];
            $v = $edge[1];
            $w = $edge[2];

            if ($distance[$u] != INF && $distance[$u] + $w < $distance[$v]) {
                echo "图中存在负权环";
                return;
            }
        }

        // 输出最短路径结果
        foreach ($this->vertices as $vertex) {
            echo "节点" . $vertex . "的最短路径长度为: " . $distance[$vertex] . ",路径为: ";
            $path = [];
            $current = $vertex;

            while ($current != $source) {
                array_unshift($path, $current);
                $current = $predecessor[$current];
            }

            array_unshift($path, $source);
            echo implode(" -> ", $path) . "
";
        }
    }
}

$graph = new Graph(["A", "B", "C", "D", "E"]);
$graph->addEdge("A", "B", 4);
$graph->addEdge("A", "C", 1);
$graph->addEdge("C", "B", -3);
$graph->addEdge("B", "D", 2);
$graph->addEdge("D", "E", 3);
$graph->addEdge("E", "D", -5);

$graph->bellmanFord("A");

Code analysis:
First, we create a The Graph class represents graphs, which include node and edge information. The edge information of the graph is stored in the edges array.

Use the addEdge method to add edge information.

The bellmanFord method implements the Bellman-Ford algorithm. First, we initialize the distance array and the predecessor node array. Then, set the source node distance to 0. Next, perform V-1 cycles on each node, where V is the number of nodes. In the loop, we check each edge and relax it if a shorter path exists. Finally, we check whether there is a negative weight cycle, and if so, print a prompt message. Finally, we output the shortest path and path length for each node.

In the sample code, we create a graph containing 5 nodes, which contains some positive and negative weight edges. Finally, we use the bellmanFord method, using "A" as the source node, to calculate the shortest path.

Summary:
This article introduces how to use PHP to implement the Bellman-Ford algorithm to solve the single-source shortest path problem in the graph. The Bellman-Ford algorithm is suitable for graphs containing negative weight edges and can detect the existence of negative weight cycles. By understanding the representation method of graphs, understanding the principles of the Bellman-Ford algorithm, and practicing it with sample codes, I believe readers will have a deeper understanding of the algorithm.

The above is the detailed content of PHP algorithm design tips: How to use the Bellman-Ford algorithm to solve the single-source shortest path problem?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn