Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit92e9779

Browse files
authored
Create 0576-out-of-boundary-paths.kt
1 parent97bfe3b commit92e9779

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Recursion + Memoization
2+
classSolution {
3+
funfindPaths(m:Int,n:Int,maxMove:Int,startRow:Int,startColumn:Int):Int {
4+
val mod=1_000_000_007
5+
val dirs= intArrayOf(0,1,0,-1,0)
6+
val dp=Array (m) {Array (n) {LongArray (maxMove+1) {-1L } } }
7+
8+
funoutOfBounds(i:Int,j:Int)= i<0|| i== m|| j<0|| j== n
9+
10+
fundfs(i:Int,j:Int,k:Int):Long {
11+
if (outOfBounds(i, j))return1L
12+
if (k==0)return0L
13+
if (dp[i][j][k]!=-1L)return dp[i][j][k]
14+
15+
dp[i][j][k]=0
16+
for (nin0..3)
17+
dp[i][j][k]= (dp[i][j][k]+ dfs(i+ dirs[n], j+ dirs[n+1], k-1))% mod
18+
19+
return dp[i][j][k]
20+
}
21+
22+
return dfs(startRow, startColumn, maxMove).toInt()
23+
}
24+
}
25+
26+
// Bottom-up DP
27+
classSolution {
28+
funfindPaths(m:Int,n:Int,maxMove:Int,startRow:Int,startColumn:Int):Int {
29+
val mod=1_000_000_007
30+
val dirs= intArrayOf(0,1,0,-1,0)
31+
val dp=Array (m) {Array (n) {LongArray (maxMove+1) } }
32+
33+
funoutOfBounds(i:Int,j:Int)= i<0|| i== m|| j<0|| j== n
34+
35+
for (kin1..maxMove) {
36+
for (iin0 until m) {
37+
for (jin0 until n) {
38+
for (dirin0..3) {
39+
val i2= i+ dirs[dir]
40+
val j2= j+ dirs[dir+1]
41+
if (outOfBounds(i2, j2))
42+
dp[i][j][k]++
43+
else
44+
dp[i][j][k]= (dp[i][j][k]+ dp[i2][j2][k-1])% mod
45+
}
46+
}
47+
}
48+
}
49+
50+
return dp[startRow][startColumn][maxMove].toInt()
51+
}
52+
}
53+
54+
// Top-down DP
55+
classSolution {
56+
funfindPaths(m:Int,n:Int,maxMove:Int,startRow:Int,startColumn:Int):Int {
57+
val mod=1_000_000_007
58+
val dirs= intArrayOf(0,1,0,-1,0)
59+
val dp=Array(m) {Array(n) {LongArray(maxMove+1) } }
60+
61+
funoutOfBounds(i:Int,j:Int)= i<0|| i== m|| j<0|| j== n
62+
63+
for (kin1..maxMove) {
64+
for (iin m-1 downTo0) {
65+
for (jin n-1 downTo0) {
66+
for (dirin0..3) {
67+
val i2= i+ dirs[dir]
68+
val j2= j+ dirs[dir+1]
69+
if (outOfBounds(i2, j2))
70+
dp[i][j][k]++
71+
else
72+
dp[i][j][k]= (dp[i][j][k]+ dp[i2][j2][k-1])% mod
73+
}
74+
}
75+
}
76+
}
77+
78+
return dp[startRow][startColumn][maxMove].toInt()
79+
}
80+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp