C 語言中的矩陣機率問題?


矩陣機率問題計算元素在採取 N 步和任意方向後位於給定矩陣內的機率。這意味著我們需要找出即使沿著任意方向移動 N 個位置,該元素也不會超出矩陣範圍的機率。

在這個問題中,我們可以自由地將矩陣元素向所有四個方向移動(左、右、上、下)。而且元素移動的機率相同,都是 0.25 或 1/4。

如果元素超出範圍,則程式將返回 0,否則不返回 0。

示例

 即時演示

#include <stdio.h>
int isSafe(int x, int y, int m, int n) {
   return (x >= 0 && x < m &&
   y >= 0 && y < n);
}
double Probability(int m, int n, int x, int y, int N) {
   if (!isSafe(x, y, m, n))
      return 0.0;
   if (N == 0)
      return 1.0;
   double prob = 0.0;
   prob += Probability(m, n, x - 1, y, N - 1) * 0.25;
   prob += Probability(m, n, x, y + 1, N - 1) * 0.25;
   prob += Probability(m, n, x + 1,y, N - 1) * 0.25;
   prob += Probability(m, n, x, y - 1, N - 1) * 0.25;
   return prob;
}
int main() {
   int m = 5, n = 5;
   int i = 2, j = 1;
   int N = 4;
   printf("Probability of moving is %lf", Probability(m, n, i, j, N));
   return 0;
}

輸出

Probability of moving is 0.738281

更新時間:04-Oct-2019

125 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.