473,609 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Qquestion on Shortest paths algorithm

Hello. I have implemented the Dijkstra shortest path algorithm, it
works fine but I have one question on how I can improve something.
I want to find all the possible shortest paths from a node since there
is a possibility to exist more than one shortest paths with the same
distance.

Does anyone has any idea how this could be done?

Code
double Dijkstra_Least_ Cost(vector< vector<int graph, int
start_vertex, ofstream &outputfile)
{
unsigned int graph_size = graph.size();
unsigned int D_size = graph_size + 1;
unsigned int ii, jj, W;
unsigned int kk = 1;
double average_distanc e = 0;
double temp_d = 0;

vector <intdistance;
vector <intpredecessor ;
vector <boolnot_checke d;
map <int,intinterme diate_nodes;
map<int, int>::const_ite rator iter;
vector< vector<int betweennes_l(D_ size, vector<int>(D_s ize,0));
outputfile <<"Starting from node: " << start_vertex << endl;

//initialize the vectors
distance.push_b ack(0); //in order to start from 1.
not_checked.pus h_back(true); //in order to start from 1.
predecessor.pus h_back(0); //in order to start from 1.
for (ii = 1; ii < graph_size; ii ++)
{
distance.push_b ack(graph[start_vertex][ii]);
not_checked.pus h_back(true);
predecessor.pus h_back(start_ve rtex);

}

distance[start_vertex] = 0; //set start distance to zero
predecessor[0] = -1;
predecessor[start_vertex] = -1; //default start predecessor

not_checked[start_vertex] = false; //mark as checked vertex

bool done = false;

int testing = 0;
while (!done)
{
int V, shortest_d = BIG;

for (jj = 1; jj < graph_size; jj ++)
{
//if it is <= we get a different route.
if (distance[jj] <= shortest_d && not_checked[jj])
{
V = jj;
shortest_d = distance[V];
}
}

not_checked[V] = false; //for every neighbor W of V

//edge relaxation
for (W = 1; W < graph_size; W++)
{
if (graph[V][W] < BIG && not_checked[W])
{ //unchecked neighbor
if (distance[W] distance[V] + graph[V][W])
{
distance[W] = distance[V] + graph[V][W];
predecessor[W] = V;
}
}

while (kk < graph_size && !not_checked[kk])
kk++;
done = (kk == graph_size);//done=true if there are no unchecked
neighbors
}
//*************** *************** *************PR INT LEAST COST TO NODES
for (ii = 1; ii < graph_size; ii++)
{
temp_d+=distanc e[ii];
outputfile << "To arrive at node " << ii << " will cost" <<
distance[ii] << endl;
}
average_distanc e = temp_d / (graph_size-2);
//-2 because we dont count itself and also
// the graph vector is 1 more than the number of nodes

//E4
cout << endl;

//*************** *************** *************PR INT LEAST COST TO NODES
cout << "Shortest Paths" << endl; //Print out all shortest paths
stack<inttemp; //No recursion- use stacks
for (ii = 1; ii < graph_size; ii++)
{
int m = ii;
int m1;

while (predecessor[m] != -1)
{
m1 = m;
temp.push(m);
//intermediate_no des[m]++; //how many times a node was used along
the
// paths. we will count the paths of length 1
m = predecessor[m];
betweennes_l[m][m1]++;
intermediate_no des[m]++; //how many times a node was used along the
//paths. we will count the paths of length 2
}

int flag = 0;

while ( !temp.empty() )
{
if (flag ==0 )
{
cout << start_vertex;
}
cout << "-"<< temp.top();
flag++;
temp.pop();
}
cout << endl;
}

for (iter=intermedi ate_nodes.begin (); iter !=
intermediate_no des.end(); ++iter)
{
if (iter->first != start_vertex)
{
cout << iter->first << ": " << iter->second << endl;
}
}
cout << endl;

cout << "Number of times each link is counted for the Shortest Path"
<< endl;

for ( ii = 1; ii < graph_size; ii++)
{
for (jj = 1; jj < graph_size; jj++)
{
if (betweennes_l[ii][jj] != 0 )
{
cout << ii << "-"<< jj << "=" << betweennes_l[ii][jj]<< endl;
}
}
}

return average_distanc e;
}

Cheers
costas

Jul 26 '06 #1
5 2872
co*********@gma il.com wrote:
Hello. I have implemented the Dijkstra shortest path algorithm, it
works fine but I have one question on how I can improve something.
I want to find all the possible shortest paths from a node since there
is a possibility to exist more than one shortest paths with the same
distance.

Does anyone has any idea how this could be done?
[snip]
//edge relaxation
for (W = 1; W < graph_size; W++)
{
if (graph[V][W] < BIG && not_checked[W])
{ //unchecked neighbor
if (distance[W] distance[V] + graph[V][W])
{
distance[W] = distance[V] + graph[V][W];
predecessor[W] = V;
}
}
[snip]

This is more of a programming question than a C++ question so you might
try comp.programmin g. To briefly address your question, you need to
modify the logic of the above snippet to include a check for dist[W] =
dist[V] + graph[V][W]. In such a case rather than replacing the
predecessor of W with V, you must add V to a list of W's predecessors.
The result is that, instead of each vertex having a path of predecessors
back to the start, each vertex has a tree of predecessors back to the
start, with each path through the tree being an equal shortest path.
Jul 26 '06 #2
Mark thanks for the reply.
you are right on some point but the problem is that over there are
passed only the values that have to do with the path that was already
selected.

mostly the problem is at

//if it is <= we get a different route.
for (jj = 1; jj < graph_size; jj ++)
{

if (distance[jj] <= shortest_d && not_checked[jj])
{
V = jj;
shortest_d = distance[V];
}
}
over there if i select <= and not < it gives another shortest path.
the first problem it that it gives only 2 shortest paths ..and there
are cases that there are more.
The second problem is that even if I can see the two paths, i cannot
store both of these paths. In order to achive it i have to modify the
code (replace < with <= ) and run it for a second time.

btw thanks for the tip. I have post it to comp.programmin g as well.

Jul 26 '06 #3
Please quote the relevant portions of the message to which you are replying.

co*********@gma il.com wrote:
Mark thanks for the reply.
you are right on some point but the problem is that over there are
passed only the values that have to do with the path that was already
selected.

mostly the problem is at

//if it is <= we get a different route.
for (jj = 1; jj < graph_size; jj ++)
{

if (distance[jj] <= shortest_d && not_checked[jj])
{
V = jj;
shortest_d = distance[V];
}
}
I don't think so. The code above is to pick out the closest vertex not
yet "finalized" , which then becomes the source for the next relaxation
pass. (And as an aside this is a pretty slow implementation since you
take O(n) time to find that vertex. The conventional approach is to use
a priority queue instead.)

In any event, look back at my earlier reply. What you call the "edge
relaxation" step is where you determine if there is a better route to a
particular vertex. What you don't check for is the case of a tie-- two
routes that are equally good. You need separate logic for the '>' case
and the '=' case, but in the '=' case you need to save all equally good
routes. As I said before, the way to do this is not to have a single
predecessor value but a collection (list, vector, whatever) of values.

Mark
Jul 27 '06 #4
Ok I can see what you are saying. I have implemented it and it works ok
now with the concept that you told me. Since my predecessor was already
a vector i constracted a map <int, vector <int>and i store all the
values of the predecessor when I have two equal length paths.
My question now is how can i retrive these paths?
Do I have to try all the possible combinations that can be made with
the vectors (I can see a solution like that) or is there any easiest
way.

Cheers Costas

Jul 27 '06 #5
co*********@gma il.com wrote:
Ok I can see what you are saying. I have implemented it and it works ok
now with the concept that you told me. Since my predecessor was already
a vector i constracted a map <int, vector <int>and i store all the
values of the predecessor when I have two equal length paths.
My question now is how can i retrive these paths?
Do I have to try all the possible combinations that can be made with
the vectors (I can see a solution like that) or is there any easiest
way.

Cheers Costas
Once again, when you reply to a post you need to quote the portion
you're replying to. Just like I've quoted above what you wrote.

The sets of predecessors define a DAG (directed acyclic graph). You'll
need to build up all possible paths from start to finish. It's not that
hard though-- you can do it recursively from the end point.
Jul 27 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2091
by: Lau | last post by:
How do I easily calculate the shortest path between two geographical spots on a map? The map is divided into zones. So I guess it is possible to use Dijkstra’s Shortest Path algorithm, but it seems like a lot of work and I am sure that it has been done many times before. From (x,y) coordinates I need to place the user in a zone and find the shortest path to all other zones. Any suggestions are more than welcome. I would hate to reinvent...
6
5878
by: ThanhVu Nguyen | last post by:
Hi all, I need recommendation for a very fast shortest path algorithm. The edges are all directed, positive weights. Dijkstra shortest path will solve it just fine but the if the graph is not parse then it takes about O(N^2) where N is the # of vertices, too much for large graphs. Furthermore, I don't need to know the all the path from a start point to every other single vertex as Dijkstra would provide. Just the shortest path from a...
20
17029
by: Webdad | last post by:
Hi! I running my first year as industrial engineer (informatics) We have an assignment to do : .... create a playfield (matrix). Some places in that field are blocked, so you can't pass them. The others are free to go over ... (I already found that part) -> http://users.pandora.be/hebbrecht/jochen/c++/test.cpp
5
7388
by: leezard | last post by:
I am developing a program using VB.NET that will accept a start and end point, the system then will generate the shortest path to reach the end point. Anyone here have idea on doing this or some code examples that can share it with me? Thanks in advance.
1
2837
by: Adam Hartshorne | last post by:
Hi All, I know how to calculate the all-pair shortest paths matrix on an undirected graph. I was wondering how I could extend this to calculate the all-pair average path, or if not a simple extension an efficient algorithm to compute this. Any help much appreciated, Adam
4
12085
by: Shuch | last post by:
Hi all, I am in shortage of time...and i want to know if someone has a code written in c++ or c for finding the shortest path using stack or queue??????my specifications r as follow: Input data: n = integer number representing the number of vertices k = small integer number representing the maximal vertex degree G = unoriented labeled connected graph G with n vertices and maximal degree k
8
4122
by: abhradwip | last post by:
I want to write a program which will find the shortest path between n no. of cities using dijkstra's algorithm ...... but could not do it..... i have written a program which will give the shortest path between finite no. of cities....... plz help me out....... i would also like to know for the states & city names should i use a database.....if so how???? Im giving the prog which ive written... plz help me with the source code........... ...
4
32062
prometheuzz
by: prometheuzz | last post by:
Hello (Java) enthusiasts, In this article I’d like to tell you a little bit about graphs and how you can search a graph using the BFS (breadth first search) algorithm. I’ll address, and hopefully answer, the following questions: • what is a graph? • how can a graph be represented as an ADT? • how can we search/walk through a graph using the BFS algorithm?
2
4650
by: shashankbs | last post by:
Given a topology and a certain node X, find the shortest path tree with X as the root. * Input: a topology file similar to the following (which is a three-node ring) -------------------------------------------- Nodes: (3) // there are three nodes (node 0, 1 and 2) Edges: (3)
0
8095
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8588
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8556
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6068
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5526
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2541
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1690
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1407
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.