1
+ class NumberOfWaysOfCuttingAPizza {
2
+ private final int modulo = (int ) (Math .pow (10 , 9 ) + 7 );
3
+
4
+ private int dfs (int m , int n , int k , int r , int c , Integer [][][] dp , int [][] preSum ) {
5
+ if (preSum [r ][c ] == 0 ) return 0 ;
6
+ if (k == 0 ) return 1 ;
7
+ if (dp [k ][r ][c ] != null ) return dp [k ][r ][c ];
8
+ int res = 0 ;
9
+ for (int nr = r + 1 ; nr < m ; nr ++) {
10
+ if (preSum [r ][c ] - preSum [nr ][c ] > 0 ) {
11
+ res = (res + dfs (m , n , k - 1 , nr , c , dp , preSum )) % modulo ;
12
+ }
13
+ }
14
+ for (int nc = c + 1 ; nc < n ; nc ++) {
15
+ if (preSum [r ][c ] - preSum [r ][nc ] > 0 ) {
16
+ res = (res + dfs (m , n , k - 1 , r , nc , dp , preSum )) % modulo ;
17
+ }
18
+ }
19
+ dp [k ][r ][c ] = res ;
20
+ return dp [k ][r ][c ];
21
+ }
22
+
23
+ public int ways (String [] pizza , int k ) {
24
+ int m = pizza .length , n = pizza [0 ].length ();
25
+ Integer [][][] dp = new Integer [k ][m ][n ];
26
+ int [][] preSum = new int [m + 1 ][n + 1 ];
27
+ for (int r = m - 1 ; r >= 0 ; r --) {
28
+ for (int c = n - 1 ; c >= 0 ; c --) {
29
+ preSum [r ][c ] = preSum [r ][c + 1 ] + preSum [r + 1 ][c ] - preSum [r + 1 ][c + 1 ] + (pizza [r ].charAt (c ) == 'A' ? 1 : 0 );
30
+ }
31
+ }
32
+ return dfs (m , n , k - 1 , 0 , 0 , dp , preSum );
33
+ }
34
+ }
0 commit comments