Posts

Showing posts from April, 2014

TSP

#include<iostream> #include<conio.h> int s,c[100][100],ver; float optimum=999,sum; using namespace std; /* function to swap array elements */ void swap(int v[], int i, int j) { int t; t = v[i]; v[i] = v[j]; v[j] = t; } /* recursive function to generate permutations */ void brute_force(int v[], int n, int i) { // this function generates the permutations of the array from element i to element n-1 int j,sum1,k; //if we are at the end of the array, we have one permutation if (i == n) { if(v[0]==s) { for (j=0; j<n; j++) cout<<"  "<<v[j]; sum1=0; for( k=0;k<n-1;k++) { sum1=sum1+c[v[k]][v[k+1]]; } sum1=sum1+c[v[n-1]][s]; cout<<" sum ="<<sum1<<endl; getch(); if (sum1<optimum) optimum=sum1; } } else // recursively explore the permutations starting at index i going through index n-1*/ for (j=i; j<n; j++) { /* try the array with i and j switched */ swap (v, i, j); brute_force (v, n, i+1); /* swap them back the way they wer
//nqueens #include<iostream> #include <conio.h> #include<math.h> #include<stdlib.h> #define max 20 using namespace std; class nqueens { private:  int n; public:     nqueens(int num); void display(int [],int); int place(int [],int); }; nqueens::nqueens(int num) {     int x[max];     int k;     n=num;     cout<<"the soln to"<<n<<"queens problem is\n";     x[0]=-1;     k=0;     while(k>=0)     {         x[k]=x[k]+1;         while(x[k]<n&&!place(x,k))         x[k]=x[k]+1;         if(x[k]<n)         if(k==n-1)         display(x,n);         else         {                 k++;                 x[k]=-1;         }         else                 k--;     } } int nqueens::place(int x[],int k) {     int i;     for(i=0;i<k;i++)         if(x[i]==x[k]||abs(x[i]-x[k])==abs(i-k))             return 0;             return 1; } void nqueens::display(int x[],int n) {     char chessb[max][max];     int i,j;     for(i=0;i<n;i