Analysis of Algorithm Computer Graphics Data Structures

Longest Common Subsequence using Dynamic Programming in C

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define SIZE 20
void display(char[][SIZE],char[],int,int);
void compute_LCS(char A[],char B[])
{
 
 int m,n,i,j;
 int c[SIZE][SIZE];
 char d[SIZE][SIZE];
 m=strlen(A);
 n=strlen(B);
 for(i=0;i<=m;i++)
  c[0][i]=0;
 for(i=0;i<=n;i++)
  c[i][0]=0;
 for(i=1;i<=m;i++)
 {
  for(j=1;j<=n;j++)
  {
   if(A[i]==B[j])
   {
    c[i][j]=c[i-1][j- 1]+1;
    d[i][j]='/';
   }
   else if(c[i-1][j]>=c[i][j- 1])
   {
    c[i][j]=c[i-1][j];
    d[i][j]='^';
   }
   else
   {
    c[i][j]=c[i][j-1];
    d[i][j]='<';
   }
  }    
 }
 printf("\nTable is...\n");
 for(i=0;i<=n;i++)
 {
  for(j=0;j<=m;j++)
  {
   printf("%3d",c[j][i]);
  }
  printf("\n");
 }
 printf("\n The Longest Common Subsequece is...");
 display(d,A,m,n);
}

void display(char d[][20],char A[],int i,int j)
{
 if (i==0||j==0)
  return;
 if(d[i][j]=='/')
 {
  display(d,A,i-1,j- 1);
  printf("%c",A[i-1]);
  
 }
 else if(d[i][j]=='^')
  display(d,A,i-1,j);
 else
  display(d,A,i,j-1);
}

int main()
{
 char A[SIZE],B[SIZE];

 printf("Enter First sequence:");
 scanf("%s",A);
 printf("Enter Second sequence:");
 scanf("%s",B);
 compute_LCS(A,B);
 getch();
}

image 1
OUTPUT

Comments

Popular posts from this blog

Cohen Sutherland Line Clipping Algorithm In C

Graph Coloring using Backtracking in C