问题描述:给出5个参数,N,M,row,col,k,表示在N * M的区域上,李四初始在(row,col)位置,他一共要迈出k步,且每步都会等概率向上下左右四个方向走一个单位,任何时候李四只要离开N*M的区域,就直接死亡,走了k步之后,李四还在N * M区域的概率,即李四活着的概率。
解决方案:暴力递归和动态规划的解决方案
1、暴力递归:
1.1、图示分析:
6*6的格子,在(3,3)位置,向四个方向移动5次,不越界的概率
1.2、核心代码:
public class NanDaoLiSiLive {
public static void main(String[] args) {
System.out.println(live1(3, 3, 5, 6, 6));
}
private static double live1(int row, int col, int k, int N, int M) {
return (double)processLive(row,col,k,N,M)/Math.pow(4,k);
}
// 目前在row,col位置,还有rest步要走,走完了如果还在棋盘中就获得1个生存点,返回总的生存点数
private static long processLive(int row, int col, int rest, int n, int m) {
if(row < 0 || row == n || col < 0 || col == m){
return 0;
}
// 还在棋盘中,返回1!
if(rest == 0){
return 1;
}
// 还在棋盘中!还有步数要走
long up = processLive(row - 1,col,rest - 1,n,m);
long down = processLive(row + 1,col,rest - 1,n,m);
long left = processLive(row,col - 1,rest - 1,n,m);
long right = processLive(row,col + 1,rest - 1,n,m);
return up + down + left + right;
}
}
2、动态规划方案:
2.1、图示分析:
2.2、核心代码:
public class NanDaoLiSiLive {
public static void main(String[] args) {
System.out.println(live2(3, 3, 5, 6, 6));
}
private static double live2(int row, int col, int k, int N, int M) {
long[][][] dp = new long[N][M][k + 1];
for(int i = 0;i < row;i++){
for(int j = 0;j < col;j++){
dp[i][j][0] = 1;
}
}
for(int rest = 1;rest <= k;rest++){
for(int r = 0;r < N;r++){
for(int c = 0;c < M;c++){
dp[r][c][rest] += pickLive(dp, N, M, r - 1, c, rest - 1);
dp[r][c][rest] += pickLive(dp, N, M, r + 1, c, rest - 1);
dp[r][c][rest] += pickLive(dp, N, M, r, c - 1, rest - 1);
dp[r][c][rest] += pickLive(dp, N, M, r, c + 1, rest - 1);
}
}
}
return (double)dp[row][col][k] / Math.pow(4,k);
}
public static long pickLive(long[][][] dp, int N, int M, int r, int c, int rest) {
if (r < 0 || r == N || c < 0 || c == M) {
return 0;
}
return dp[r][c][rest];
}
}
到此,此算法分析结束,下期更精彩,敬请期待!