题目
一个 N x M 大小的棋盘,从任意位置开始,每次往上下左右任意方向走一步,如果超出棋盘范围那么就失败,求走 k 步后存活的概率
- 构造上下左右的递归结构,求出所有生存的方法数,然后/所有的方法,所有方法的总数为 4 的 k 次方,因为每次可能走4步,一共走 k 次
function process(row, column, x, y, step) {
// 从0开始计数,棋盘大小是9行10列
if (x < 0 || x === column || y < 0 || y === row) {
return 0;
}
if (step === 0) {
return 1;
}
return (
process(row, column, x - 1, y, step - 1) +
process(row, column, x + 1, y, step - 1) +
process(row, column, x, y + 1, step - 1) +
process(row, column, x, y - 1, step - 1)
);
}
const res= process(...) / Math.pow(4 , k)