NodeJs语言实现最短路径算法(Shortest Path)

NodeJs语言实现最短路径算法(Shortest Path)

在Node.js中实现最短路径算法,可以使用Dijkstra算法。以下是一个使用Dijkstra算法来计算图中单源最短路径的示例:

class PriorityQueue {
    constructor() {
        this.collection = [];
    }

    enqueue(element) {
        if (this.isEmpty()) {
            this.collection.push(element);
        } else {
            let added = false;
            for (let i = 0; i < this.collection.length; i++) {
                if (element[1] < this.collection[i][1]) { // checking priorities
                    this.collection.splice(i, 0, element);
                    added = true;
                    break;
                }
            }
            if (!added) {
                this.collection.push(element);
            }
        }
    }

    dequeue() {
        return this.collection.shift();
    }

    isEmpty() {
        return (this.collection.length === 0);
    }
}

class Graph {
    constructor(vertices) {
        this.vertices = vertices;
        this.adjacencyList = new Map();
    }

    addVertex(vertex) {
        this.adjacencyList.set(vertex, []);
    }

    addEdge(source, target, weight) {
        this.adjacencyList.get(source).push({ node: target, weight: weight });
        this.adjacencyList.get(target).push({ node: source, weight: weight }); // 如果是有向图,则去掉这一行
    }

    dijkstra(startVertex) {
        let distances = {};
        let pq = new PriorityQueue();
        let previous = {};

        this.adjacencyList.forEach((_, vertex) => {
            distances[vertex] = Infinity;
            previous[vertex] = null;
        });
        distances[startVertex] = 0;

        pq.enqueue([startVertex, 0]);

        while (!pq.isEmpty()) {
            let [currentVertex, currentDistance] = pq.dequeue();

            this.adjacencyList.get(currentVertex).forEach(neighbor => {
                let distance = currentDistance + neighbor.weight;

                if (distance < distances[neighbor.node]) {
                    distances[neighbor.node] = distance;
                    previous[neighbor.node] = currentVertex;
                    pq.enqueue([neighbor.node, distance]);
                }
            });
        }

        this.printShortestPaths(startVertex, distances);
    }

    printShortestPaths(startVertex, distances) {
        console.log(`Vertex\tDistance from Source ${startVertex}`);
        for (let vertex in distances) {
            console.log(`${vertex}\t\t${distances[vertex]}`);
        }
    }
}

// 示例使用
let graph = new Graph(6);
['A', 'B', 'C', 'D', 'E', 'F'].forEach(vertex => graph.addVertex(vertex));
graph.addEdge('A', 'B', 4);
graph.addEdge('A', 'C', 3);
graph.addEdge('B', 'C', 1);
graph.addEdge('B', 'D', 2);
graph.addEdge('C', 'D', 4);
graph.addEdge('D', 'E', 2);
graph.addEdge('E', 'F', 6);

graph.dijkstra('A');

在这个示例中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们从顶点'A'开始运行Dijkstra算法,计算并打印出从顶点'A'到所有其他顶点的最短路径距离。代码使用了自定义的PriorityQueue类来实现优先队列,以确保每次都选择距离最短的顶点进行处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚丁号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值