题目描述
现在有两个好友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(2 ≤ N,M ≤ 20, k ≤ 100),N,M为草地大小,接下来K行,每行两个整数x,y,代表(x,y)处有一个蘑菇。
输出描述:
输出一行,代表所求概率(保留到2位小数)
输入例子:
2 2 1
2 1
输出例子:
0.50
import java.util.Scanner;
/**
* 若她在边界上,则只有一种选择
* j==m右边界,i==n下边界,只有一种选择,概率为1(i,j>1,即走向右上角和左下角概率0.5)
* Created by ustc-lezg on 16/4/11.
*/
public class Main {
public static void main(String[] args) {
calPro();
}
private static void calPro() {
Scanner scanner = new Scanner(System.in);
int n, m, k;
while (scanner.hasNext()) {
boolean[][] grid = new boolean[22][22];
double[][] p = new double[22][22];
n = scanner.nextInt();
m = scanner.nextInt();
k = scanner.nextInt();
int x, y;
if (k == 0) {
System.out.println("1.00");
continue;
}
for (int i = 0; i < k; i++) {
x = scanner.nextInt() - 1;
y = scanner.nextInt() - 1;
grid[x][y] = true;
}
if (grid[0][0] || grid[n - 1][m - 1]) {
System.out.println("0.00");
continue;
}
p[0][0] = 1;
for (int i = 1; i < n; i++) {
if (grid[i][0]) {
break;
} else {
p[i][0] = p[i - 1][0] * 0.5;
}
}
for (int i = 1; i < m; i++) {
if (grid[0][i]) {
break;
} else {
p[0][i] = p[0][i - 1] * 0.5;
}
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (grid[i][j]) {
p[i][j] = 0;
} else {
p[i][j] = (j == m - 1 ? 1 : 0.5) * p[i - 1][j] + (i == n - 1 ? 1 : 0.5) * p[i][j - 1];
}
}
}
System.out.println(String.format("%.2f", p[n - 1][m - 1]));
}
scanner.close();
}
}