简体   繁体   中英

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? It has 1 if there is an edge between 2 vertices and 0 otherwise. The explanations that I've found on the internet are all for graphs with costs.

Dijkstra's algorithm requires edge cost to work. 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.

In that case, you can just assume that every edge has cost 1, and Dijkstra's algorithm will work as intended. 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.

After that the algorithm just worked as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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