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
| class Solution { public static final int MOD = (int) 1e9 + 7;
public int ways(String[] pizza, int k) { MatrixSum ms = new MatrixSum(pizza); return dfs(k - 1, 0, 0, ms, pizza.length, pizza[0].length()); }
private int dfs(int c, int i, int j, MatrixSum ms, int m, int n) { if (c == 0) return ms.query(i, j, m, n) > 0 ? 1 : 0; int ans = 0; for (int j2 = j; j2 < n; ++j2) { if (ms.query(i, j, m, j2) > 0) { ans = (ans + dfs(c - 1, i, j2, ms, m, n)) % MOD; } } for (int i2 = i; i2 < m; ++i2) { if (ms.query(i, j, i2, n) > 0) { ans = (ans + dfs(c - 1, i2, j, ms, m, n)) % MOD; } } return ans; }
private static class MatrixSum {
private final int[][] sum;
public MatrixSum(String[] matrix) { int m = matrix.length, n = matrix[0].length(); sum = new int[m + 1][n + 1]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + (matrix[i].charAt(j) & 1); } } }
public int query(int r1, int c1, int r2, int c2) { return sum[r2][c2] - sum[r2][c1] - sum[r1][c2] + sum[r1][c1]; } } }
|