题目描述
现在有两个好友A和B,住在一片长有蘑菇的由n*m个方格组成的草地,A在(1,1),B在(n,m)。现在A想要拜访B,由于她只想去B的家,所以每次她只会走(i,j+1)或(i+1,j)这样的路线,在草地上有k个蘑菇种在格子里(多个蘑菇可能在同一方格),问:A如果每一步随机选择的话(若她在边界上,则只有一种选择),那么她不碰到蘑菇走到B的家的概率是多少?
输入描述:
第一行N,M,K(1 ≤ N,M ≤ 20, k ≤ 100),N,M为草地大小,接下来K行,每行两个整数x,y,代表(x,y)处有一个蘑菇。
输出描述:
输出一行,代表所求概率(保留到2位小数)
动态规划过程
以4*4为例
代码:
while True:
try:
n,m,k = map(int, input().split())
mashroom = []
dp = [[1.0 for i in range(m)] for j in range(n)]
for _ in range(k):
x,y = map(int, input().split())
mashroom.append([x-1,y-1])
for i in range(n):
for j in range(m):
if [i,j] in mashroom:
dp[i][j] = 0
elif i == 0 and j == 0:
dp[i][j] = 1.0
elif i == 0:
dp[i][j] = dp[i][j-1]*(1 if i == n-1 else 0.5)
elif j == 0:
dp[i][j] = dp[i-1][j]*(1 if j == m-1 else 0.5)
else:
dp[i][j] = dp[i-1][j]*(1 if j == m-1 else 0.5) + dp[i][j-1]*(1 if i == n-1 else 0.5)
print('%.2f' % dp[n-1][m-1])
except:
break
错误思路:
经过蘑菇路径的数量/总路径的数量;每条路径走的概率不同,使用不能这么求;
总路径的数量:
经过蘑菇路径的数量:
代码:
while True:
try:
n,m,k=[int(x) for x in input().split()]
vers=[[0 for i in range(m)] for j in range(n)]
ver_1=[[0 for i in range(m)] for j in range(n)]
ver_2=[[0 for i in range(m)] for j in range(n)]
for i in range(k):
x,y=[int(j) for j in input().split()]
vers[x-1][y-1]=1
# print(vers)
for i in range(n-1,-1,-1):
for j in range(m-1,-1,-1):
if i==n-1 and j==m-1:
ver_1[i][j]=1
else:
if i==n-1:
ver_1[i][j]=ver_1[i][j+1]
if vers[i][j]==1:
ver_2[i][j]=ver_1[i][j]
else:
ver_2[i][j] = ver_2[i][j+1]
elif j==m-1:
ver_1[i][j]=ver_1[i+1][j]
if vers[i][j]==1:
ver_2[i][j]=ver_1[i][j]
else:
ver_2[i][j] = ver_2[i+1][j]
else:
ver_1[i][j]=ver_1[i+1][j]+ver_1[i][j+1]
# vers[i][j] = max(vers[i + 1][j]+vers[i][j+1],vers[i][j])
if vers[i][j]==1:
ver_2[i][j]=ver_1[i][j]
else:
ver_2[i][j] = ver_2[i + 1][j]+ver_2[i][j+1]
# print(ver_1[0][0])
# print(ver_2)
print("{:.2f}".format((ver_1[0][0]-ver_2[0][0])/ver_1[0][0]))
except:
break