华为机试---蘑菇阵(动态规划)



题目描述

现在有两个好友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;
 
public class Main {
 public static void main(String[] args){
  Scanner scan = new Scanner(System.in);
  while(scan.hasNext()){
   int N = scan.nextInt();
            int M = scan.nextInt();
            int K = scan.nextInt();
            int[][] route = new int[N + 1][M + 1];
            for(int i = 0 ; i < K ; i++){
             int x = scan.nextInt();
                int y = scan.nextInt();
                route[x][y] = 1;//有蘑菇的标记位为1,其余为0
            }            
            double[][] probability = new double[N + 1][M + 1];
            probability[1][1] = 1;
            for(int i = 1 ; i <= N ; i++){
             for(int j = 1 ; j <= M ; j++){
              if(i == 1 && j == 1) continue;
              if(route[i][j] == 1){
               //格子里有蘑菇
               probability[i][j] = 0;
              }else{
               //格子里没有蘑菇
               if(i == N && j == M){
                probability[i][j] = probability[i - 1][j] + probability[i][j - 1];
               }else if(i == N){
                probability[i][j] = probability[i - 1][j] * 0.5 + probability[i][j - 1];
               }else if(j == M){
                probability[i][j] = probability[i][j - 1] * 0.5 + probability[i - 1][j];
               }else{
                probability[i][j] = probability[i - 1][j] * 0.5 + probability[i][j - 1]* 0.5;
               }
              }
             }
            }//endfor
            System.out.printf("%.2f\n" , probability[N][M]);
  }   
  scan.close();
    }
}
 
 

你可能感兴趣的:(java,华为)