Skip to content

Instantly share code, notes, and snippets.

/Dijk

Created October 4, 2010 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/609214 to your computer and use it in GitHub Desktop.
Save anonymous/609214 to your computer and use it in GitHub Desktop.
#include<iostream>
using namespace std;
#define infi 999
class queue
{
private:
int q[100];
int front, rear;
protected:
queue()
{
front = rear = -1;
}
int isempty()
{
if ((front == -1 && rear == -1) || (front > rear))
{
front = rear = -1;
return 1;
}
return 0;
}
void push(int a)
{
if (isempty())
front++;
q[++rear] = a;
};
int del()
{
return q[front++];
}
};
class dj : public queue
{
private:
int mat[20][20], dist[20], path[20];
public:
int n;
void input()
{
cout << "Enter number of nodes:\n";
cin >> n;
cout << "\n\nEnter adjacency matrix\n" << endl;
for (int i = 1;i <= n;i++)
{
cout << " enter the weights of row " << i <<" : ";
for (int j = 1;j <= n;j++)
cin >> mat[i][j];
}
}
void init(int m)
{
push(m);
dist[m] = 0;
for (int i = 1;i <= n;i++)
{
if (i != m)
{
push(i);
dist[i] = infi;
}
path[i] = 0;
}
}
void min_dist(int m)
{
int v, w;
init(m);
while (!(isempty()))
{
v = del();
cout << "this is v del " <<v <<endl;
for (int i = 1;i <= n;i++)
{
if (mat[v][i] != 0)
{
w = i;
if ((dist[v] + mat[v][w]) < (dist[w]))
{
dist[w] = dist[v] + mat[v][w];
path[w] = v;
}
}
}
}
}
void disp_path(int m)
{
int p = path[m];
if (p == 0)
return;
disp_path(p);
cout << " " << m;
}
void disp_dist(int m)
{
cout << "Cost: " << dist[m] << endl << endl;
}
};
int main()
{
int startnode,endnode;
char answer;
dj a;
a.input();
do
{
cout << "start node: ";
cin >> startnode;
cout << "end node: ";
cin >> endnode;
a.min_dist(startnode);
cout<<"\nFrom "<<startnode<<" to "<<endnode<<":"<<endl;
cout<<"------------"<<endl;
cout<<"Minimum distance route: ("<<startnode;
a.disp_path(endnode);
cout<<")"<<endl;
a.disp_dist(endnode);
cout << "Do you want to calculate another path (Y/N)? ";
cin >> answer;
} while (answer != 'n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment