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
| class Solution { int ans, n, m; boolean[][] rect;
public int tilingRectangle(int n, int m) { ans = Math.max(n, m); rect = new boolean[n][m]; this.n = n; this.m = m; dfs(0, 0, 0); return ans; }
public void dfs(int x, int y, int cnt) { if (cnt >= ans) return; if (x >= n) { ans = cnt; return; } if (y >= m) { dfs(x + 1, 0, cnt); return; } if (rect[x][y]) { dfs(x, y + 1, cnt); return; }
for (int k = Math.min(n - x, m - y); k >= 1 && isAvailable(rect, x, y, k); --k) { fill(x, y, k, true); dfs(x, y + k, cnt + 1); fill(x, y, k, false); } }
private boolean isAvailable(boolean[][] rect, int x, int y, int k) { for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { if (rect[x + i][y + j]) { return false; } } } return true; }
private void fill(int x, int y, int k, boolean flag) { for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { rect[x + i][y + j] = flag; } } } }
|