Sie sind auf Seite 1von 13

Prims

#include<stdio.h>
#include<stdlib.h>
 
#define infinity 9999
#define MAX 20
 
int G[MAX][MAX],spanning[MAX][MAX],n;
 
int prims();
 
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

total_cost=prims();
printf("\nspanning tree matrix:\n");

for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}

printf("\n\nTotal cost of spanning tree=%d",total_cost);


return 0;
}
 
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;

//create cost[][] matrix,spanning[][]


for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}

//initialise visited[],distance[] and from[]


distance[0]=0;
visited[0]=1;

for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}

min_cost=0; //cost of spanning tree


no_of_edges=n-1; //no. of edges to be added

while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}

u=from[v];

//insert the edge in spanning tree


spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;

//updated the distance[] array


for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}

min_cost=min_cost+cost[u][v];
}

return(min_cost);
}

Kruskal
#include<stdio.h>
 
#define MAX 30
 
typedef struct edge
{
int u,v,w;
}edge;
 
typedef struct edgelist
{
edge data[MAX];
int n;
}edgelist;
 
edgelistelist;
 
int G[MAX][MAX],n;
edgelistspanlist;
 
void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();
 
int main()
{
int i,j,total_cost;

printf("\nEnter number of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

kruskal();
print();
return 0;
}
 
void kruskal()
{
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;
 
for(i=1;i<n;i++)
for(j=0;j<i;j++)
{
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
}
}
 
sort();

for(i=0;i<n;i++)
belongs[i]=i;

spanlist.n=0;

for(i=0;i<elist.n;i++)
{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);

if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
}
}
 
int find(int belongs[],int vertexno)
{
return(belongs[vertexno]);
}
 
void union1(int belongs[],int c1,int c2)
{
int i;

for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}
 
void sort()
{
int i,j;
edge temp;

for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}
 
void print()
{
int i,cost=0;

for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}
 
printf("\n\nCost of the spanning tree=%d",cost);
}

Dijkstra’s program
#include<stdio.h>
#include<stdlib.h>
#define INFINITY 9999
#define MAX 10
 
void dijkstra(int G[MAX][MAX],int n,int startnode);
 
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");


scanf("%d",&u);
dijkstra(G,n,u);

return 0;
}
 
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
 
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node


//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]


for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}

distance[startnode]=0;
visited[startnode]=1;
count=1;

while(count<n-1)
{
mindistance=INFINITY;

//nextnode gives the node at minimum distance


for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}

//check if a better path exists through nextnode


visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
 
//print the path and distance of each node
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

Floyd
#include<stdio.h>
int min(int,int);
void floyds(int p[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
else
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
}
int min(int a,int b)
{
if(a<b)
return(a);
else
return(b);
}
void main()
{
int p[10][10],w,n,e,u,v,i,j;;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
p[i][j]=999;
}
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge%d with its weight \n",i);
scanf("%d%d%d",&u,&v,&w);
p[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
floyds(p,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",p[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,p[i][j]);
}
}

Warshal: -

#include<stdio.h>
const int MAX = 100;

void WarshallTransitiveClosure(int graph[MAX][MAX], int numVert);


int main(void)
{
int i, j, numVert;
int graph[MAX][MAX];

printf("Warshall's Transitive Closure\n");


printf("Enter the number of vertices : ");
scanf("%d",&numVert);

printf("Enter the adjacency matrix :-\n");


for (i=0; i<numVert; i++)
for (j=0; j<numVert; j++)
scanf("%d",&graph[i][j]);

WarshallTransitiveClosure(graph, numVert);

printf("\nThe transitive closure for the given graph is :-\n");


for (i=0; i<numVert; i++)
{
for (j=0; j<numVert; j++)
{
printf("%d\t",graph[i][j]);
}
printf("\n");
}

return 0;
}

void WarshallTransitiveClosure(int graph[MAX][MAX], int numVert)


{
int i,j,k;

for (k=0; k<numVert; k++)


{
for (i=0; i<numVert; i++)
{
for (j=0; j<numVert; j++)
{
if (graph[i][j] || (graph[i][k] && graph[k][j]))
graph[i][j] = 1;
}
}
}
}

Knapsack: -
#include<stdio.h>

int max(int a, int b) { return (a > b)? a : b; }

int knapSack(int W, int wt[], int val[], int n)


{
   int i, w;
   int K[n+1][W+1];

   for (i = 0; i <= n; i++)


   {
       for (w = 0; w <= W; w++)
       {
           if (i==0 || w==0)
               K[i][w] = 0;
           else if (wt[i-1] <= w)
                 K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]);
           else
                 K[i][w] = K[i-1][w];
       }
   }

   return K[n][W];
}

int main()
{
    int i, n, val[20], wt[20], W;
    
    printf("Enter number of items:");
    scanf("%d", &n);
    
    printf("Enter value and weight of items:\n");
    for(i = 0;i < n; ++i){
     scanf("%d%d", &val[i], &wt[i]);
    }
 
    printf("Enter size of knapsack:");
    scanf("%d", &W);
    
    printf("%d", knapSack(W, wt, val, n));
    return 0;
}

Output: -

Enter number of items:3


Enter value and weight of items:
100 20
50 10
150 30
Enter size of knapsack:50
250

N Queens: -
#include<stdio.h>
#include<math.h>
 
int board[20],count;
 
int main()
{
int n,i,j;
void queen(int row,int n);
 
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
 
//function for printing the solution
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
 
for(i=1;i<=n;++i)
  printf("\t%d",i);
 
for(i=1;i<=n;++i)
{
  printf("\n\n%d",i);
  for(j=1;j<=n;++j) //for nxn board
  {
   if(board[i]==j)
    printf("\tQ"); //queen at i,j position
   else
    printf("\t-"); //empty slot
  }
}
}
 
/*funtion to check conflicts
If no conflict for desired postion returns 1 otherwise returns 0*/
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
  //checking column and digonal conflicts
  if(board[i]==column)
   return 0;
  else
   if(abs(board[i]-column)==abs(i-row))
    return 0;
}
 
return 1; //no conflicts
}
 
//function to check for proper positioning of queen
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
  if(place(row,column))
  {
   board[row]=column; //no conflicts so place queen
   if(row==n) //dead end
    print(n); //printing the board configuration
   else //try queen with next position
    queen(row+1,n);
  }
}
}

Output: -

Travelling salesman problem: -


#include<stdio.h>
int a[10][10],n,visit[10];
int cost_opt=0,cost_apr=0;
int least_apr(int c);
int least_opt(int c);

void mincost_opt(int city)
{
            int i,ncity;
            visit[city]=1;
            printf("%d-->",city);
            ncity=least_opt(city);
            if(ncity==999)
            {
                        ncity=1;
                        printf("%d",ncity);
                        cost_opt+=a[city][ncity];
                        return;
            }
            mincost_opt(ncity);
}
 void mincost_apr(int city)
 {
            int i,ncity;
            visit[city]=1;
            printf("%d-->",city);
            ncity=least_apr(city);
            if(ncity==999)
            {
                        ncity=1;
                        printf("%d",ncity);
                        cost_apr+=a[city][ncity];
                        return;
            }
            mincost_apr(ncity);
}

int least_opt(int c)
{
            int i,nc=999;
            int min=999,kmin=999;
            for(i=1;i<=n;i++)
            {
                        if((a[c][i]!=0)&&(visit[i]==0))
                        if(a[c][i]<min)
                        {
                                    min=a[i][1]+a[c][i];
                                    kmin=a[c][i];
                                    nc=i;
                        }
            }
            if(min!=999)
                        cost_opt+=kmin;
            return nc;
}

int least_apr(int c)
{
            int i,nc=999;
            int min=999,kmin=999;
for(i=1;i<=n;i++)
            {
                        if((a[c][i]!=0)&&(visit[i]==0))
                                    if(a[c][i]<kmin)
                                    {
                                                min=a[i][1]+a[c][i];
                                                kmin=a[c][i];
                                                nc=i;
                                    }
            }
            if(min!=999)
                        cost_apr+=kmin;
            return nc;
}
 void main()
{
            int i,j;
            printf("Enter No. of cities:\n");
            scanf("%d",&n);

            printf("Enter the cost matrix\n");


            for(i=1;i<=n;i++)
            {
                        printf("Enter elements of row:%d\n",i );
                        for(j=1;j<=n;j++)
                                    scanf("%d",&a[i][j]);
                        visit[i]=0;
            }
            printf("The cost list is \n");
            for(i=1;i<=n;i++)
            {
                        printf("\n\n");
                        for(j=1;j<=n;j++)
                                    printf("\t%d",a[i][j]);
            }
            printf("\n\n Optimal Solution :\n");
            printf("\n The path is :\n");
            mincost_opt(1);
            printf("\n Minimum cost:");
            printf("%d",cost_opt);
            printf("\n\n Approximated Solution :\n");
            for(i=1;i<=n;i++)
                        visit[i]=0;
            printf("\n  The path is :\n");
            mincost_apr(1);
            printf("\nMinimum cost:");
            printf("%d",cost_apr);
            printf("\n\nError in approximation is approximated solution/optimal solution=%f",
                        (float)cost_apr/cost_opt);
}

OUTPUT 1 :

Enter No. of cities:


4
Enter the cost matrix
Enter elements of row:1
0136
Enter elements of row:2
1023
Enter elements of row:3
3201
Enter elements of row:4
6310

The cost list is

            0          1          3          6

            1          0          2          3

            3          2          0          1

            6          3          1          0

 Optimal Solution :

 The path is :
1-->2-->4-->3-->1
 Minimum cost:8

 Approximated Solution :

  The path is :
1-->2-->3-->4-->1
Minimum cost:10

Error in approximation is approximated solution/optimal solution=1.250000

Das könnte Ihnen auch gefallen