Merge pull request #107 from nikhilarora068/master

added knight tour to backtracking and longest common string to dynamic
This commit is contained in:
Ashwek Swamy 2019-11-07 00:15:34 +05:30 committed by GitHub
commit 41a95c2989
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 124 additions and 0 deletions

View File

@ -0,0 +1,59 @@
#include<bits/stdc++.h>
# define n 8
using namespace std;
bool issafe(int x,int y,int sol[n][n])
{
return (x<n && x>=0 && y<n && y>=0 && sol[x][y]==-1);
}
bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n])
{
int k,xnext,ynext;
if(mov == n*n)
return true;
for(k=0;k<8;k++)
{
xnext=x+xmov[k];
ynext=y+ymov[k];
if(issafe(xnext,ynext,sol))
{
sol[xnext][ynext]=mov;
if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true)
return true;
else
sol[xnext][ynext]=-1;
}
}
return false;
}
int main()
{
//initialize();
int sol[n][n];
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
sol[i][j]=-1;
int xmov[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int ymov[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
sol[0][0]=0;
bool flag=solve(0,0,1,sol,xmov,ymov);
if(flag==false)
cout<<"solution doesnot exist \n";
else
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
cout<<sol[i][j]<<" ";
cout<<"\n";
}
}
}

View File

@ -0,0 +1,65 @@
#include<bits/stdc++.h>
using namespace std;
int max(int a,int b)
{
return (a > b) ? a : b;
}
int main()
{
char str1[]="DEFBCD";
char str2[]="ABDEFJ";
int i,j,k;
int n=strlen(str1)+1;
int m=strlen(str2)+1;
//cout<<n<<" "<<m<<"\n";
int a[m][n];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i==0 || j==0)
a[i][j]=0;
else if(str1[i-1] == str2[j-1])
a[i][j]=a[i-1][j-1]+1;
else
a[i][j]=0;
}
}
/*for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<"\n";
}*/
int ma=-1;
int indi,indj;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]>ma)
{
ma=a[i][j];
indi=i;
indj=j;
}
}
}
cout<<str1<<"\n";
cout<<str2<<"\n";
cout<<"longest string size = "<<ma/*<<" "<<indi<<" "<<indj*/<<"\n";
for(i=indi-3;i<indi;i++)
cout<<str1[i];
cout<<"\n";
}