You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.
You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.
Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.
Use dynamic programming to track the maximum score and the number of ways to reach each cell, moving only up, left, or diagonally up-left, and avoiding obstacles.
classSolution {
funpathsWithMaxScore(board: List<String>): IntArray {
val n = board.size
val MOD = 1_000_000_007
val score = Array(n) { IntArray(n) }
val ways = Array(n) { IntArray(n) }
ways[n-1][n-1] = 1for (i in n-1 downTo 0) {
for (j in n-1 downTo 0) {
if (board[i][j] =='X'|| (i == n-1&& j == n-1)) continuevar maxScore = -1var cnt = 0for ((di, dj) in listOf(i+1 to j, i to j+1, i+1 to j+1)) {
if (di < n && dj < n && ways[di][dj] > 0) {
val s = score[di][dj]
if (s > maxScore) {
maxScore = s
cnt = ways[di][dj]
} elseif (s == maxScore) {
cnt = (cnt + ways[di][dj]) % MOD
}
}
}
if (maxScore == -1) continueval valCell = if (board[i][j] =='E') 0else board[i][j] - '0' score[i][j] = maxScore + valCell
ways[i][j] = cnt
}
}
returnif (ways[0][0] ==0) intArrayOf(0,0) else intArrayOf(score[0][0], ways[0][0])
}
}
classSolution:
defpathsWithMaxScore(self, board: list[str]) -> list[int]:
n, MOD = len(board), 10**9+7 score = [[0]*n for _ in range(n)]
ways = [[0]*n for _ in range(n)]
ways[n-1][n-1] =1for i in range(n-1, -1, -1):
for j in range(n-1, -1, -1):
if board[i][j] =='X'or (i == n-1and j == n-1): continue maxScore, cnt =-1, 0for di, dj in [(i+1,j),(i,j+1),(i+1,j+1)]:
if di < n and dj < n and ways[di][dj] >0:
s = score[di][dj]
if s > maxScore:
maxScore = s
cnt = ways[di][dj]
elif s == maxScore:
cnt = (cnt + ways[di][dj]) % MOD
if maxScore ==-1: continue val =0if board[i][j] =='E'else int(board[i][j])
score[i][j] = maxScore + val
ways[i][j] = cnt
return [0,0] if ways[0][0] ==0else [score[0][0], ways[0][0]]