File tree Expand file tree Collapse file tree 1 file changed +28
-17
lines changed
src/main/kotlin/g2601_2700/s2684_maximum_number_of_moves_in_a_grid Expand file tree Collapse file tree 1 file changed +28
-17
lines changed Original file line number Diff line number Diff line change 11package g2601_2700.s2684_maximum_number_of_moves_in_a_grid
22
33// #Medium #Array #Dynamic_Programming #Matrix
4- // #2023_07_28_Time_542_ms_ (100.00%)_Space_57.4_MB_(57.14 %)
4+ // #2023_09_19_Time_509_ms_ (100.00%)_Space_67.9_MB_(25.00 %)
55
66class Solution {
77 fun maxMoves (grid : Array <IntArray >): Int {
8- val height = grid.size
9- val width = grid[0 ].size
10- val dp = Array (height) { IntArray (width) { Int .MIN_VALUE } }
11- var result = 0
12- for (i in 0 until height) {
13- dp[i][0 ] = 0
14- }
15- for (c in 1 until width) {
16- for (r in 0 until height) {
17- if (r > 0 && grid[r - 1 ][c - 1 ] < grid[r][c]) {
18- dp[r][c] = dp[r][c].coerceAtLeast(dp[r - 1 ][c - 1 ] + 1 )
8+ val h = grid.size
9+ var dp1 = BooleanArray (h)
10+ var dp2 = BooleanArray (h)
11+ var rtn = 0
12+ dp1.fill(true )
13+ for (col in 1 until grid[0 ].size) {
14+ var f = false
15+ for (row in 0 until h) {
16+ val pr = row - 1
17+ val nr = row + 1
18+ dp2[row] = false
19+ if (pr >= 0 && dp1[pr] && grid[pr][col - 1 ] < grid[row][col]) {
20+ dp2[row] = true
21+ f = true
22+ }
23+ if (nr < h && dp1[nr] && grid[nr][col - 1 ] < grid[row][col]) {
24+ dp2[row] = true
25+ f = true
1926 }
20- if (grid[r][c - 1 ] < grid[r][c ]) dp[r][c] = dp[r][c].coerceAtLeast(dp[r][c - 1 ] + 1 )
21- if (r < height - 1 && grid[r + 1 ][c - 1 ] < grid[r][c]) {
22- dp[r][c] = dp[r][c].coerceAtLeast(dp[r + 1 ][c - 1 ] + 1 )
27+ if (dp1[row] && grid[row][col - 1 ] < grid[row][col ]) {
28+ dp2[row] = true
29+ f = true
2330 }
24- result = result.coerceAtLeast(dp[r][c])
2531 }
32+ val t = dp1
33+ dp1 = dp2
34+ dp2 = t
35+ if (! f) break
36+ rtn++
2637 }
27- return result
38+ return rtn
2839 }
2940}
You can’t perform that action at this time.
0 commit comments