Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<limits.h>
- #include<stdbool.h>
- int Graph[100][100];
- int d[100];
- int w[100][100];
- int path[100];
- bool visited[100];
- //int queue[100];
- int i,j,k,vertex,edge,start,end,Source;
- int stack[100], top=-1;
- void push(int node)
- {
- stack[++top] = node;
- }
- int pop()
- {
- return (stack[top--]);
- }
- int isEmptyStack()
- {
- if(top == -1)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- void inputGraph()
- {
- printf("Enter number of vertex : ");
- scanf("%d",&vertex);
- printf("Enter number of Edge:");
- scanf("%d", &edge);
- for(i=1; i<=edge; i++)
- {
- printf("Enter edge %d: ",i);
- scanf("%d %d",&start,&end);
- Graph[start][end] = 1;
- //Graph[end][start] = 1;
- printf("Weight: ");
- scanf("%d",&w[start][end]);
- }
- printf("MATRIX REPRESENTATION OF THE GRAPH:\n");
- for(i=1; i<=vertex; i++)
- {
- for(j=1; j<=vertex; j++)
- printf("%d ",Graph[i][j]);
- printf("\n");
- }
- }
- void inputSource()
- {
- printf("\nEnter Source:");
- scanf("%d", &Source);
- }
- void Initilize_Single_Source(int Source)
- {
- int j;
- for(j=1; j<=vertex; j++)
- {
- path[j]=0;
- d[j]=9999;
- }
- d[Source]=0;
- }
- void Relax(int u,int v)
- {
- if(d[v] > d[u]+ w[u][v])
- {
- d[v] = d[u] + w[u][v];
- path[v] = u;
- }
- }
- int Extract_Min()
- {
- int min_dis = 9999,unvisitedVertex;
- for(i=1; i<=vertex; i++)
- {
- if(!visited[i] && min_dis >= d[i])
- {
- min_dis = d[i];
- unvisitedVertex = i;
- }
- }
- return unvisitedVertex;
- }
- void Dijkstra(int Source)
- {
- Initilize_Single_Source(Source);
- int i,j,each_vertex=0,u,v;
- while(each_vertex<vertex)
- {
- u = Extract_Min();
- visited[u]=true;
- for(i=1; i<=vertex; i++)
- {
- for(j=1; j<=vertex; j++)
- {
- if(Graph[i][j])
- {
- Relax(i,j);
- }
- }
- }
- each_vertex++;
- }
- }
- void print()
- {
- printf("Cost : Path\n");
- for(i=1; i<=vertex; i++)
- {
- if(d[i]<9999)
- printf("%d : ",d[i]);
- else
- printf("\nInfinity\n: ");
- push(i);
- while(stack[top]!=0)
- {
- push(path[stack[top]]);
- }
- while(!isEmptyStack())
- {
- if(stack[top]!=0)
- printf("%d -> ",stack[top]);
- pop();
- }
- printf("End!\n");
- }
- }
- int main()
- {
- inputGraph();
- inputSource();
- Dijkstra(Source);
- print();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement