我的代码:
int MOD = 1000000007;
int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
int dx[4] = { 0,0,-1,1 };
int dy[4] = { -1,1,0,0 };
long long dp[50 + 1][50 + 1][50 + 1];
memset(dp, 0, sizeof(dp));
for (int x = 0; x < m; x++)
{
for (int y = 0; y < n; y++)
{
for (int i = 0; i < 4; i++)
{
int newx = x + dx[i];
int newy = y + dy[i];
if ((newx < 0 || newx >= m) || (newy < 0 || newy >= n))
{
dp[x][y][1]++;
}
}
}
}
for (int i = 2; i <= maxMove; i++)
{
for (int x = 0; x < m; x++)
{
for (int y = 0; y < n; y++)
{
for (int j = 0; j < 4; j++)
{
int newx = x + dx[j];
int newy = y + dy[j];
if ((newx >= 0 && newx < m) && (newy >= 0 && newy < n))
{
dp[x][y][i] = (dp[newx][newy][i - 1]%MOD-dp[newx][newy][i-2]%MOD+MOD
+dp[x][y][i]%MOD)%MOD;
}
}
dp[x][y][i] = (dp[x][y][i - 1]%MOD+dp[x][y][i]%MOD)%MOD;
}
}
}
return dp[startRow][startColumn][maxMove];
}
官方代码:
int MOD = 1000000007;
int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int outCounts = 0;
int dp[maxMove + 1][m][n];
memset(dp, 0, sizeof(dp));
dp[0][startRow][startColumn] = 1;
for (int i = 0; i < maxMove; i++) {
for (int j = 0; j < m; j++) {
for (int k = 0; k < n; k++) {
int count = dp[i][j][k];
if (count > 0) {
for (int s = 0; s < 4; s++) {
int j1 = j + directions[s][0], k1 = k + directions[s][1];
if (j1 >= 0 && j1 < m && k1 >= 0 && k1 < n) {
dp[i + 1][j1][k1] = (dp[i + 1][j1][k1] + count) % MOD;
} else {
outCounts = (outCounts + count) % MOD;
}
}
}
}
}
}
return outCounts;
}