一、问题介绍
给定五个参数n,m,i,j,k。表示在一个n*m的区域,Bob处在(i,j)点,每次Bob等概率的向上、 下、左、右四个方向移动一步,Bob必须走k步。如果走完之后,Bob还停留在这个区域上, 就算Bob存活,否则就算Bob死亡。请求解Bob的生存概率,返回字符串表示分数的方式。
二、算法思路
先求出Bob在走k步条件下存活的可能数,然后求出所有的可能数,二者相除即可。
三、代码实现
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
long gcd(int a, int b)
{
int tmp;
while (b > 0)
{
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
//N*M的区域,从(row,col)出发,继续走rest步,返回生存方法数
long process1(int N, int M, int row, int col, int rest)
{
//正常情况下范围为0~N-1,0~M-1;若越界,直接返回0种生存方法
if (row < 0 || row == N || col < 0 || col == M)
return 0;
if (rest == 0)//没越界并且走完了,那么活下来了
return 1;
//没走完,也还没越界
long live = process1(N, M, row - 1, col, rest - 1);//向上
live += process1(N, M, row + 1, col, rest - 1);//向下
live += process1(N, M, row, col - 1, rest - 1);//向左
live += process1(N, M, row, col + 1, rest - 1);//向右
return live;
}
void Bob1(int N, int M, int row, int col, int k)
{
long live = process1(N, M, row, col, k);//活下来可能性
long all = (long)pow(4, k);//所有可能性
long gcd1 = gcd(all, live);
printf("%ld/%ld\n", live / gcd1, all / gcd1);
}
int dp[100][100][100] = { 0 };
long process2(int N, int M, int row, int col, int k)
{
//正常情况下范围为0~N-1,0~M-1;若越界,直接返回0种生存方法
if (row <= 0 || row > N || col <= 0 || col > M)
return 0;
//base case: 没步数了,并且还在范围内
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
dp[i][j][0] = 1;
for (int rest = 1; rest <= k; rest++)
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= M; j++)
{
dp[i][j][rest] += dp[i - 1][j][rest-1];
dp[i][j][rest] += dp[i + 1][j][rest-1];
dp[i][j][rest] += dp[i][j + 1][rest-1];
dp[i][j][rest] += dp[i][j - 1][rest-1];
}
}
}
return dp[row + 1][col + 1][k];//为避免越界,整体移动一格
}
void Bob2(int N, int M, int row, int col, int k)
{
long live = process2(N, M, row, col, k);//活下来可能性
long all = (long)pow(4, k);//所有可能性
long gcd1 = gcd(all, live);
printf("%ld/%ld\n", live / gcd1, all / gcd1);
}
int main()
{
Bob1(9, 9, 3, 3, 10);
Bob2(9, 9, 3, 3, 10);
}