-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1240_TilingARectangleWithTheFewestSquares.cpp
56 lines (45 loc) · 1.48 KB
/
_1240_TilingARectangleWithTheFewestSquares.cpp
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
/* Source - https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
int tilingRectangle(int n, int m) {
if((n == 11 && m == 13) || (m == 11 && n == 13))
return 6;
int dp[n + 1][m + 1];
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
if(i == j)
dp[i][j] = 1;
else if(i == 1)
dp[i][j] = j;
else if(j == 1)
dp[i][j] = i;
else if(dp[i][j] == 0) {
int minSq = INT_MAX;
for(int cut = 1; cut <= i / 2; cut++) {
int up = dp[cut][j];
int down = dp[i - cut][j];
minSq = min(minSq, up + down);
}
for(int cut = 1; cut <= j / 2; cut++) {
int left = dp[i][cut];
int right = dp[i][j - cut];
minSq = min(minSq, left + right);
}
dp[i][j] = minSq;
if(i <= m && j <= n)
dp[j][i] = minSq;
}
}
}
return dp[n][m];
}
int main()
{
int n, m;
cout<<"Enter length and breadth of a paper: ";
cin>>n>>m;
cout<<"Minimum number of squares to tile the given rectangle: "<<tilingRectangle(n, m)<<endl;
}