动态规划算法--Bob的生存概率

一、问题介绍

        给定五个参数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);
}

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大王算法

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值