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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP