I really could use some help with my asigment.
As it is in the title, I have to write program, based on non weighted and undirected graph, which will find shortest path between two locations. There are like 25 locations and I figured out that the fastest way to declare them is by adjacent matrix. It would be hard to define ~100 branch or lists for 25 vertexes.
I've started with small numbers just to figure out algorithm first and i have major problem.
Here is how declared graph looks like :
graph.jpg 14.08K
37 downloadsIm trying to figure it out by myself, but I've read some codes and pseudocodes, If any of them is based on matrix is directed :(
Here is my code :
#include <cstdlib>
#include <iostream>
const int n =7;
int number[7]= {1,2,3,4,5,6,7};
char *name[7]={"One","Two","Three","Four","Five","Six","Seven"};
using namespace std;
struct graph {
int L[n][n];
int numbersVisited[30]; // for saving numbers(names) of visited vertex
int tempNumber[30];
int visited;
graph ();
void MatrixShow();
void find(int start, int dest);
void search(int max, int dest, int temp);
};
graph :: graph ()
{
for (int i=0;i<n;i++) // inserting '0'
{
for (int j=0;j<n;j++)
L[i][j]=0;
}
// Inserting connections
L[0][2]=1;
L[0][4]=1;
L[1][3]=1;
L[1][4]=1;
L[2][3]=1;
L[2][4]=1;
L[3][5]=1;
L[5][6]=1;
// Graph is undirected so matrix is symetric -> Matrix[m][n]=Matrix[n][m];
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
if(L[i][j])
L[j][i]=L[i][j];
}
}
}
void graph::MatrixShow()
{
cout <<"Graph nxn : \n";
for (int i=0;i<=n;i++)
{
cout << (i)<< " ";
for (int j=0;j<n;j++)
{
if (i==0)
{
for (int k=1; k<=n;k++)
{ cout << k << " "; }
j=n;
}
if (i)
{cout << L[(i-1)][j] << " "; }
}
cout <<endl;
}
}
void graph::search (int max, int dest,int temp)
{
if(max>visited)
{
if (L[temp][dest])
{
cout << "Connection found\n";
visited++;
tempNumber[visited]=temp;
}
if (!L[temp][dest])
{
visited++;
tempNumber[visited]=temp;
for (int i=0;i<n;i++)
{
if (L[i][temp])
search(max,dest,i);
}
}
}
}
void graph::find(int start, int dest)
{
start-=1;
dest-=1;
if(L[start][dest]==1)
{
cout <<"Station "<< name[start]<<" and " << name[dest]
<< " is directly connected.\n";
}
if (!L[start][dest])
{
int max=8;
visited=0;
int temp=start;
tempNumber[0]=number[start];
for (int i=0;i<n;i++)
{
cout << i;
if (L[start][i])
{
visited=0;
search(max,dest,i);
if (visited<max)
{
max = visited;
for (int j=0; j<max;j++)
{ numbersVisited[j]=tempNumber[j]; }
}
}
}
}
}
int main(int argc, char *argv[])
{
graph G;
G.MatrixShow();
int a,b;
cout << "\nStart and destination " ;
cin >> a >> b;
cout << endl;
G.find(a,b);
system("PAUSE");
return EXIT_SUCCESS;
}


Sign In
Create Account


Back to top









