0

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.

2
  • 5
    Just assume all edges have cost 1. Commented Apr 17, 2015 at 12:14
  • See [Calcuating the shortest path between any two vertices u,v in G][1]. [1]: stackoverflow.com/questions/29512280/… Commented Apr 17, 2015 at 12:53

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

Comments

2

If you have no weights, you could either use Dijkstra and define weight = 1 for all edges or use a BFS, which is basically a special case of Dijkstra but without weighted edges.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.