简体   繁体   English

Python中邻接矩阵的Dijkstra算法

[英]Dijkstra's algorithm on adjacency matrix in python

How can I use Dijkstra's algorithm on an adjacency matrix with no costs for edges in Python? 如何在不使用Python边缘成本的邻接矩阵上使用Dijkstra的算法? It has 1 if there is an edge between 2 vertices and 0 otherwise. 如果在2个顶点之间存在边,则为1,否则为0。 The explanations that I've found on the internet are all for graphs with costs. 我在互联网上找到的解释都是针对带有成本的图表。

Dijkstra's algorithm requires edge cost to work. Dijkstra的算法需要一定的成本才能工作。 If you want to run the algorithm on a graph with "no costs", I'll assume that you're trying to find the shortest path between 2 vertices in terms of number of edges in the path. 如果要在“无成本”的图形上运行算法,则假定您要尝试根据路径的边数找到2个顶点之间的最短路径。

In that case, you can just assume that every edge has cost 1, and Dijkstra's algorithm will work as intended. 在这种情况下,您可以假设每个边的成本为1,而Dijkstra的算法将按预期工作。 Make also sure that you ignore non-existing edges in your search (you don't want the zeroes in the matrix to be counted as zero-cost edges). 还请确保忽略搜索中不存在的边(您不希望将矩阵中的零计为零成本边)。

如果没有权重,则可以使用Dijkstra并为所有边缘定义weight = 1或使用BFS ,这基本上是Dijkstra的特例,但没有加权边缘。

When I had to implement Dijkstra's algorithm in php to find the shorter way between 2 tables of a database, I constructed the matrix with 3 values : 0 if the 2 points are the same, 1 if they are linked by an edge, -1 otherwise. 当我必须在php中实现Dijkstra的算法以查找数据库的2个表之间的更短路径时,我用3个值构造了矩阵:如果2个点相同,则为0;如果它们由边链接,则为1;否则为-1 。

After that the algorithm just worked as intended. 之后,该算法就可以按预期工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM