Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest path in a map

I have designed a weighted graph using a normalized adjacency list in mysql. Now I need to find the shortest path between two given nodes.

I have tried to use Dijkstra in php but I couldnt manage to implement it (too difficult for me). Another problem I felt was that if I use Dijkstra I would need to consider all the nodes, that may be perhaps very inefficient in a large graph. So does anybody has a code relating to the above problem? It would be great if somebody atleast shows me a way of solving this problem. I have been stuck here for almost a week now. Please help.

like image 640
5lackp1x3l0x17 Avatar asked Jan 22 '23 21:01

5lackp1x3l0x17


1 Answers

This sounds like a classic case of the A* algorithm, but if you can't implement Dijkstra, I can't see you implenting A*.

A* on Wikipedia

edit: this assumes that you have a good way to estimate (but it is crucial you don't over-estimate) the cost of getting from one node to the goal.

edit2: you are having trouble with the adjacency list representation. It occurs to me that if you create an object for each vertex in the map then you can link directly to these objects when there is a link. So what you'd have essentially is a list of objects that each contain a list of pointers (or references, if you will) to the nodes they are adjacent to. Now, if you want to access the path for a new node, you just follow the links. Be sure to maintain a list of the paths you've followed for a given vertex to avoid infinite cycles.

As far as querying the DB each time you need to access something, you're going to need to do this anyway. Your best hope is to only query the DB when you NEED to... this means only querying it when you want to get info on a specific edge in the graph, or for all edges for one vertext in the graph (the latter would likely be the better route) so you only hit the slow I/O once in a while rather than gigantic chunks all at once.

like image 76
San Jacinto Avatar answered Jan 25 '23 11:01

San Jacinto