-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathEditDistance(DP).cpp
More file actions
54 lines (47 loc) · 1.16 KB
/
EditDistance(DP).cpp
File metadata and controls
54 lines (47 loc) · 1.16 KB
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
/*The idea is if the character is same then print the diagonal element
in that dp matrix else find the minimum of previous columm,row and diagonal
element and set minimum at the current position in dp matirx and at last
print the last row and column value as it will give us the minimum*/
Space Complexity : O(n^2)
Time Complexity : O(n^2)
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int minimum(int a,int b,int c)
{
int result = min(min(a,b),c);
return result;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int p,q;
cin>>p>>q;
char s1[p];
char s2[q];
cin>>s1>>s2;
//cout<<s1<<" "<<s2;
int dp[p+1][q+1];
for(int i=0;i<p+1;i++)
{
for(int j=0;j<q+1;j++)
{
if(i == 0)
dp[i][j] = j;
else if(j == 0)
dp[i][j] = i;
else if(s1[i-1] == s2[j-1])
dp[i][j] = dp[i-1][j-1];
else
{
dp[i][j] = 1 + minimum(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]);
}
}
}
cout<<dp[p][q]<<endl;
}
return 0;
}