473,545 Members | 2,073 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

plz help me about Dijkstra's algorithm

4 New Member
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...........

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <limits.h>
  3. #include <assert.h>
  4. #include <conio.h>
  5.  
  6. typedef enum {false, true} bool;
  7. typedef char *string;
  8.  
  9.  
  10. #define oo UINT_MAX 
  11.  
  12. typedef unsigned int value;
  13.  
  14. typedef enum { KOLKATA, MUMBAI, CHENNAI, BANGALORE, PUNE, DELHI, BHUBANESWAR, HYDERBAAD, nonexistent} vertex;
  15.  
  16. const vertex first_vertex = KOLKATA;
  17. const vertex last_vertex = HYDERBAAD;
  18.  
  19. #define no_vertices 8 
  20.  
  21.  
  22.  
  23. string name[] = {"KOLKATA","MUMBAI","CHENNAI","BANGALORE","PUNE","DELHI", "BHUBANESWAR", "HYDERBAAD"};
  24.  
  25.  
  26.  
  27.  
  28. value weight[no_vertices][no_vertices] =
  29.   {
  30.    /*  KOLKATA  MUMBAI CHENNAI BANGALORE  PUNE DELHI BHUBANESWAR HYDERBAAD  */
  31.     {    0,   339,  2555,    oo,    oo,    oo,    oo,    oo}, /* KOLKATA */
  32.     {   oo,    0,   337,  1843,    oo,    oo,    oo,    oo}, /* MUMBAI */
  33.     { 2555,  337,     0,  1743,  1233,    oo,    oo,    oo}, /* CHENNAI */
  34.     {   oo, 1843,  1743,     0,   802,    oo,   849,    oo}, /* BANGALORE */
  35.     {   oo,   oo,  1233,   802,     0,  1387,    oo,  1120}, /* PUNE */
  36.     {   oo,   oo,    oo,    oo,  1387,     0,   142,  1099}, /* DELHI */
  37.     {   oo,   oo,    oo,   849,    oo,   142,     0,  1205}, /* BHUBANESWAR */
  38.     {   oo,   oo,    oo,    oo,  1120,  1099,   1205,    0}  /* HYDERBAAD */
  39.   };
  40.  
  41.  
  42.  
  43.  
  44. value D[no_vertices];
  45. bool tight[no_vertices];
  46. vertex predecessor[no_vertices];
  47.  
  48.  
  49.  
  50. vertex minimal_nontight() {
  51.  
  52.   vertex j, u;
  53.  
  54.   for (j = first_vertex; j <= last_vertex; j++)
  55.      if (!tight[j])
  56.     break;
  57.  
  58.   assert(j <= last_vertex);
  59.  
  60.   u = j;
  61.  
  62.  
  63.  
  64.  
  65.  
  66.   for (j++; j <= last_vertex; j++)
  67.      if (!tight[j]  &&  D[j] < D[u])
  68.       u = j;
  69.  
  70.  
  71.  
  72.   return u;
  73. }
  74.  
  75.  
  76.  
  77. bool successor(vertex u, vertex z) {
  78.   return (weight[u][z] != oo  &&  u != z);
  79. }
  80.  
  81.  
  82.  
  83.  
  84. void dijkstra(vertex s) {
  85.  
  86.   vertex z, u;
  87.   int i;
  88.  
  89.   D[s] = 0;
  90.  
  91.   for (z = first_vertex; z <= last_vertex; z++) {
  92.  
  93.     if (z != s)
  94.       D[z] = oo;
  95.  
  96.     tight[z] = false;
  97.     predecessor[z] = nonexistent;
  98.   }
  99.  
  100.   for (i = 0; i < no_vertices; i++) {
  101.  
  102.     u = minimal_nontight();
  103.     tight[u] = true;
  104.  
  105.  
  106.  
  107.     if (D[u] == oo)
  108.       continue; /* to next iteration ofthe for loop */
  109.  
  110.     for (z = first_vertex; z <= last_vertex; z++)
  111.       if (successor(u,z) && !tight[z] && D[u] + weight[u][z] < D[z]) {
  112.     D[z] = D[u] + weight[u][z]; /* Shortcut found. */
  113.     predecessor[z] = u;
  114.       }
  115.   }
  116. }
  117.  
  118.  
  119.  
  120.  
  121. #define stack_limit 10000 /* Arbitrary choice. Has to be big enough to
  122.                  accomodate the largest path. */
  123.  
  124. vertex stack[stack_limit];
  125. unsigned int sp = 0; /* Stack pointer. */
  126.  
  127. void push(vertex u) {
  128.   assert(sp < stack_limit); /* We abort if the limit is exceeded. This
  129.                    will happen if a path with more
  130.                    vertices than stack_limit is found. */
  131.   stack[sp] = u;
  132.   sp++;
  133. }
  134.  
  135. bool stack_empty() {
  136.   return (sp == 0);
  137. }
  138.  
  139. vertex pop() {
  140.   assert(!stack_empty()); /* We abort if the stack is empty. This will
  141.                  happen if this program has a bug. */
  142.   sp--;
  143.   return stack[sp];
  144. }
  145.  
  146. /* End of stack digression and back to printing paths. */
  147.  
  148.  
  149. void print_shortest_path(vertex origin, vertex destination) {
  150.  
  151.   vertex v;
  152.  
  153.   assert(origin != nonexistent  &&  destination != nonexistent);
  154.  
  155.   dijkstra(origin);
  156.  
  157.   printf("The shortest path from %s to %s is:\n\n",
  158.      name[origin], name[destination]);
  159.  
  160.   for (v = destination; v != origin; v = predecessor[v])
  161.     if (v == nonexistent) {
  162.       printf("nonexistent (because the graph is disconnected).\n");
  163.       return;
  164.     }
  165.     else
  166.       push(v);
  167.  
  168.   push(origin);
  169.  
  170.   while (!stack_empty())
  171.     printf(" %s",name[pop()]);
  172.  
  173.   printf(".\n\n");
  174. }
  175.  
  176.  
  177. /* We now run an example. */
  178.  
  179. int main() {
  180.   clrscr();
  181.   print_shortest_path(KOLKATA,PUNE);
  182.    getch();
  183.   return 0; /* Return gracefully to the caller of the program
  184.            (provided the assertions above haven't failed). */
  185. }
Mar 20 '07 #1
8 4108
sicarie
4,677 Recognized Expert Moderator Specialist
So what are you having trouble with? Are you getting any errors, and if so, what are they? Or are you just not getting a correct answer, and what inputs are you using?
Mar 20 '07 #2
abhradwip
4 New Member
no.....actually i have done this program for only 8 cities....& have defined the aadjacent matrix within the code...... im getting the output correctly ....but if i want this program for n number of cities, then what to do?
Mar 21 '07 #3
DeMan
1,806 Top Contributor
It may be tedious, but you could use linked lists instead of arrays, otherwise, if there are n cities (and if you don't know what n is) they must come from somwhere (eg std input), you can count them as there input (storing them temporarily in a linked list), and then create matrices the size you like afterward....

Alternatively (assuming you're allowed to get rid of the matrix), you create a graph. A graph is like a linked list, but can go in more than 2 directions (so it contains a linked list of neighbors, say). Any Node stores only the cities it Neighbors, along with the weight for that particular city. This would also modify your code for Djikstra's alg, but it would probably be more efficient, because you only need to try the routes that are possible (that is, you know that a tight node will always be in the list of the current node).

Hope this is helpful, if not (I know I can be confusing) please post again....
Mar 21 '07 #4
abhradwip
4 New Member
thanx buddy.......... ......for your help...but the thing is that its little bit confusing.....

let me tell you the problem.....

suppose there is a chart like this

Source Destination

State City Area State City Area

now i have to find the shortest path from same city but different area....or different city & area..... like a flight journey...

buddy this is my main project...& i have to submit it on monday

If u can Plz help me with the source code......im very confused....... plz help me
Mar 22 '07 #5
DeMan
1,806 Top Contributor
You can find the details of Djikstra's algorithmhere

in other words....
Take the Node along the shortest path from the curerent Node (this is why we stored the weights in the Node) and add him to an "active Nodes" storing also the total weight to get this far. Choose the next shortest total path (which may be the shortest node at your new node, or the second shortest at your old one)....Continu e to do this until you arrive at your destination
Mar 22 '07 #6
abhradwip
4 New Member
i am getting u ......... but to build this algo..is a very tough task.......that s yyy im requesting u to plz provide me with the code.....for n no. of cities.
Mar 22 '07 #7
Roonie
99 New Member
- ahem -

you learning how to build tough algorithms yourself is what its all about. if you dont really want to learn how to program, you should not be doing it.
Mar 22 '07 #8
DeMan
1,806 Top Contributor
As Roonie said, we can offer help, but ultimately you still have to do the work. Perhaps if you can explain where the difficulty lies, we may be able to help you through it.

Alternatively, if you can attempt the problem (and find it doesn't compile, it gives unsexpected output etc), we may be able to help you fix some of the problems.

Maybe to begibn with, you should consider what sort of methods you might need and what they would do. You should also consider Data Structures you may need and how you would go about im[plementing them.
Then you can try to convert the algorithm on the net (or my english version) into some form of pseudocode to work out what you are doing.....

Hope this helps
Mar 22 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2537
by: Der Andere | last post by:
Do you know of an efficient implementation (priority queues) of Dijkstra's algorithm for calculating the shortest distances between vertices in a graph? Cheers, Matthias -- Für emails Anweisung in der Adresse befolgen
2
2920
by: A_StClaire_ | last post by:
hi, I am trying to do this thing in C# and was wondering if it's customary for the algorithm to backtrack. is its purpose only to find the shortest path from a to z, or does one normally implement it backward (i.e., z to a) after going forward? obviously we are assuming edges may not be equal when reversing directions (e.g., takes...
3
5009
by: Ook | last post by:
This is probably a bit OT, as I'm not looking for a c++ implementaiton of Dijkstra's algorithm, rather I'm just trying to understand it (is there a better place then here to ask this question?). I've reviewed several sites and the faq (no, I'm not asking you to do my homework for me) and the examples don't give me the information I need to...
9
4497
by: Josh Zenker | last post by:
I've been working on an implementation of Dijkstra's algorithm on and off for the past few days. I thought I was close to being finished, but clearly I've done something wrong. I'm not a very experienced programmer, so please be patient. My code compiles in g++ without any errors or warnings. Unfortunately it segfaults when it runs. I...
0
1640
momotaro
by: momotaro | last post by:
am having a final tomorrow am not yet done with dijkstra!!! plz help this is my code waht is wrong with it! void Dijkstra(char *root, char *destination, GraphNode *head) { GraphNode *Root, *dest, *GraphNodeWalker, *vertmin; ListNode *ListNodeWalker; int flag;
3
7825
by: victorporton | last post by:
D.K. is traveling from City A to City B. He can stop at some designated spots only. I am trying to use Dijkstra’s algorithm to determine the “spot-to-spot” path that will get D.K. from City A to the City B in the minimum amount of time. The input in my program is an integer n and the 2D coordinates of n spots. Some assumptions have been...
2
4642
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)
1
14192
by: Glenton | last post by:
Hi All Here is a very simple little class for finding a shortest route on a network, following Dijkstra's Algorithm: #!/usr/bin/env python #This is meant to solve a maze with Dijkstra's algorithm from numpy import inf from copy import copy
1
2904
by: Greg Jackson | last post by:
Hello, I am having some trouble in working out the distance of each node from the starting node in my Dijkstra Algorithm code. Here is my code with the section i'm stuck on in bold: infinity = 1000000 invalid_node = -1 startNode = 0 class Node: distFromSource = infinity
0
7470
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7659
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. ...
1
7428
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7760
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5334
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...
0
3444
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1887
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
1019
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
709
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...

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.