Skip to content

Commit d10b8ac

Browse files
Merge pull request #539 from SOUHARDYAADHIKARY1999/master
longest common subsequence added
2 parents 3b15cdf + d9e7c59 commit d10b8ac

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

C/lcs.c

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include<stdio.h>
2+
#include<stdlib.h>
3+
#include<string.h>
4+
void printMat(int** ar,int n,int m)
5+
{
6+
int i = 0,j = 0;
7+
for(i =0 ; i< n ;i++)
8+
{
9+
for(j = 0; j< m; j++)
10+
{
11+
printf("%d\t", ar[i][j]);
12+
}
13+
printf("\n" );
14+
}
15+
}
16+
void LCSPrint(char* X, int** dir, int n, int m)
17+
{
18+
//printf("%d-%d-%d\n",dir[n][m],n,m );
19+
if(dir[n][m]==1)
20+
{
21+
LCSPrint(X,dir,n-1,m-1);
22+
printf("%c",X[m-1] );
23+
}
24+
else if(dir[n][m] == 2)
25+
{
26+
LCSPrint(X, dir, n-1,m);
27+
}
28+
else if(dir[n][m]==3)
29+
{
30+
LCSPrint(X,dir,n,m-1);
31+
}
32+
}
33+
void LCS(char* p1, char* p2, int n1, int n2)
34+
{
35+
int i = 0, j= 0;
36+
n1++;
37+
n2++;//Important
38+
int **ar = (int**)calloc(n1,sizeof(int*));
39+
int **dir = (int**)calloc(n1,sizeof(int*));
40+
for(i = 0; i< n1+1; i++)
41+
{
42+
ar[i] = (int*)calloc(n2,sizeof(int));
43+
dir[i] = (int*)calloc(n2,sizeof(int));
44+
}
45+
for(i = 1; i< n1; i++)
46+
{
47+
for(j = 1;j< n2; j++)
48+
{
49+
if(p1[i-1] == p2[j-1])
50+
{
51+
ar[i][j] = ar[i-1][j-1]+1;
52+
dir[i][j] = 1;
53+
}
54+
else
55+
{
56+
if(ar[i-1][j] >= ar[i][j-1])
57+
{
58+
ar[i][j] = ar[i-1][j];
59+
dir[i][j] = 2;
60+
}
61+
else
62+
{
63+
ar[i][j] = ar[i][j-1];
64+
dir[i][j] = 3;
65+
}
66+
}
67+
}
68+
}
69+
printMat(ar,n1,n2);
70+
printf("=========\n" );
71+
printMat(dir,n1,n2);
72+
LCSPrint(p2,dir,n1-1,n2-1);
73+
}
74+
int main()
75+
{
76+
char X[] = "ABCBDAB";
77+
char Y[] = "BDCABA";
78+
79+
int m = strlen(X);
80+
int n = strlen(Y);
81+
LCS(X,Y,m,n);
82+
}

0 commit comments

Comments
 (0)