- #include<stdio.h>
- #include<limits.h>
- int n;
- int adj[10][10],vi[10];
- int dist[10];
- void shortest(int v);
- int min();
- int main(){
- int i,j,s;
- printf("enter number of vertices\n");
- scanf("%d",&n);
- for(i=1;i<=n;i++){
- dist[i]=INT_MAX;
- printf("%d\t",dist[i]);
- }
- printf("enter adjacency matrix\n");
- for(i=1;i<=n;i++)
- for(j=1;j<=n;j++)
- scanf("%d",&adj[i][j]);
- printf("enter source vertex to start\n");
- scanf("%d",&s);
- shortest(s);
- printf("shortest distances from vertex %d are\n",s);
- for(i=1;i<=n;i++){
- if(dist[i]<INT_MAX&&vi[i]==1)
- printf("cost:%d\tedge:(%d,%d)\n",dist[i],s,i);
- }
- return 0;
- }
- void shortest(int v){
- int i,j,u;
- for(i=1;i<=n;i++){
- vi[i]=-1;
- if(adj[v][i]!=0)
- dist[i]=adj[v][i];
- }
- vi[v]=1;
- for(j=2;j<=n;j++){
- u=min();
- printf("%d\n",u);
- vi[u]=1;
- for(i=1;i<=n;i++){
- if((adj[u][i]!=0)&&(dist[i]>(dist[u]+adj[u][i]))&&(vi[i]==-1)){
- dist[i]=(dist[u]+adj[u][i]);
- }
- }
- }
- return;
- }
- int min(){
- int i,t=dist[1],j;
- for(i=1;i<=n;i++){
- if((dist[i]<t)&&(vi[i]==-1))
- {
- t=dist[i];
- }}
- for(j=1;j<=n;j++){
- if(t==dist[j]&&vi[j]==-1)
- break;}
- return j;
- }
This blog will serve the purpose for all types of c programs and all technology related details
Showing posts with label Greedy Algorithms. Show all posts
Showing posts with label Greedy Algorithms. Show all posts
Thursday, 22 February 2018
SINGLE SOURCE SHORTEST PATH PROBLEM(DIJKSTRA'S ALGORITHM) 'C' PROGRAM
Subscribe to:
Posts (Atom)
FERMATS LITTLE THEOREM
import java.math.*; import java.io.*; import java.util.Scanner; public class Main { public static void main(String[] args) { Sca...
-
#include<stdio.h> #define m1 100 int m,n,avail[m1],max[m1],alloc[m1][m1],need[m1][m1],safe[m1],req[m1][m1]; void result(){ int i,...
-
import java.math.*; import java.io.*; import java.util.Scanner; public class Main { public static void main(String[] args) { Sca...