Algorithm Assignment
Algorithm Assignment
3) Write an algorithm to find out the Permutation of given string with output.
Code:
#include <bits/stdc++.h>
using namespace std;
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
int main()
{
int m;
//clrscr();
cout <<"Enter no of vertices:";
cin >> n;
cout <<"Enter no of edges:";
cin >> m;
cout <<"\nEDGES \n";
for(k=1; k<=m; k++)
{
cin >>i>>j;
cost[i][j]=1;
}
cout <<"Enter initial vertex to traverse from:";
cin >>v;
cout <<"DFS ORDER OF VISITED VERTICES:";
cout << v <<" ";
visited[v]=1;
k=1;
while(k<n)
{
for(j=n; j>=1; j--)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
cout<<v << " ";
k++;
visit[v]=0;
visited[v]=1;
}
return 0;
}
Output:
2) Write an algorithm to implement Kruskal’s algorithm with output.
Code:
#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
void main()
{
Output:
3) Write an algorithm to find out the Permutation of given string with output.
Code:
#include<bits/stdc++.h>
using namespace std;
void swap(char *x, char *y)
{
char temp ;
temp = *x;
*x = *y;
*y = temp;
}
void permutation(char *a, int l, int r)
{
if(l==r)
{
cout<<a<<endl;
}
else
{
int i;
for(i=l;i<=r;i++)
{
swap(a+l,a+i);
permutation(a,l+1,r);//Backtracking
swap(a+l,a+i);
}
}
}
int main()
{
char s[100];
cout<<"Enter the string to find out its Permutation :"<<endl;
cin>>s;
int l = strlen(s);
cout<<"The Permutation of given string are:"<<endl;
permutation(s,0,l-1);
return 0;
}
Output:
4) Write an algorithm to implement Prims algorithm with output.
Code:
#include <bits/stdc++.h>
using namespace std;
#define INF 9999999
#define V 5
int G[V][V] = { {0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
int main () {
return 0;
}
Output:
5) Write an algorithm to implement travellingSalesman problem with output.
Code:
#include<bits/stdc++.h>
using namespace std;
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
completed[i]=0;
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
if(min!=999)
cost+=kmin;
return nc;
}
completed[city]=1;
cout<<city+1<<"--->";
ncity=least(city);
if(ncity==999)
{
ncity=0;
cout<<ncity+1;
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}
int main()
{
takeInput();