LWC 52:688. Knight Probability in Chessboard

LWC 52:688. Knight Probability in Chessboard

传送门:688. Knight Probability in Chessboard

Problem:

On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.

Example:

Input: 3, 2, 0, 0 Output: 0.0625 Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625.

Note:

N will be between 1 and 25.

K will be between 0 and 100.

The knight always initially starts on the board.

思路: 一开始采用BFS来遍历所有情况,但在OJ上内存溢出且超时了,主要原因在于BFS把所有的状态都跑一边,而此处K相对较大,N却较小,所以骑士在经过k步之后,很有可能在图中经过相同的点,只是对应的k不同罢了。

初始代码如下:

    int[][] dir = {{2, 1},{2, -1},{-2, -1},{-2, 1},{1, 2},{1, -2},{-1, 2},{-1, -2}};

    class Pair{
        int id;
        double pro;

        Pair(int id, double pro){
            this.id = id;
            this.pro = pro;
        }
    }

    public double knightProbability(int N, int K, int r, int c) {

        Queue<Pair> queue = new ArrayDeque<>();
        queue.offer(new Pair(r * N + c, 1));

        int turn = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; ++i) {
                Pair p = queue.poll();
                int cnt = 0;
                List<Integer> tmp = new ArrayList<>();  
                for (int[] d : dir) {
                    int nx = d[0] + p.id / N;
                    int ny = d[1] + p.id % N;
                    if (check(nx, ny, N)) {
                        cnt ++;
                        tmp.add(nx * N + ny);
                    }
                }
                for (int j = 0; j < tmp.size(); ++j) {
                    queue.offer(new Pair(tmp.get(j), p.pro * cnt / 8));
                }
            }
            turn ++;
            if (turn == K) break; 
        }

        double ans = 0;
        int size = queue.size();
        while (!queue.isEmpty()) {
            ans += (queue.poll().pro / size);
        }

        return ans;
    }

    boolean check(int i, int j, int N) {
        return i >= 0 && i < N && j >= 0 && j < N;
    }

这里遇到重复子问题的多次计算,定义问题为f(i, j, k)表示当前坐标(i, j)下,骑士k次移动后的概率。如何划分子问题呢?因为它有八个方向可以移动,所以有:f(i + d[x][0], j + d[x][1], k - 1), x = 1,2,...,8,表示移动到八个位置的其中一个后,原问题变成了如上子问题。

所以,我们有递归+记忆化的手段,代码如下:

    int[][] dir = {{2, 1},{2, -1},{-2, -1},{-2, 1},{1, 2},{1, -2},{-1, 2},{-1, -2}};

    double[][][] mem = new double[102][32][32];
    public double f(int N, int K, int R, int C) {
        if (K == 0) {
            return 1;
        }
        if (mem[K][R][C] > 0) return mem[K][R][C];
        double res = 0.0;
        for (int[] d : dir) {
            int nx = R + d[0];
            int ny = C + d[1];
            if (check(nx, ny, N)) {
                res += 1 / 8.0 * f(N, K - 1, nx, ny);
            }
        }

        return mem[K][R][C] = res;
    }

    public void fill(double[][][] mem) {
        for (int i = 0; i < mem.length; ++i) {
            for (int j = 0; j < mem[i].length; ++j) {
                for (int k = 0; k < mem[i][j].length; ++k) {
                    mem[i][j][k] = -1;
                }
            }
        }
    }

    boolean check(int i, int j, int N) {
        return i >= 0 && i < N && j >= 0 && j < N;
    }


    public double knightProbability(int N, int K, int r, int c) {
        fill(mem);
        return f(N, K, r, c);
    }

当然,你可以直接把它改成自底向上的迭代形式(动态规划)。代码如下:

    int[][] dir = {{2, 1},{2, -1},{-2, -1},{-2, 1},{1, 2},{1, -2},{-1, 2},{-1, -2}};

    boolean check(int i, int j, int N) {
        return i >= 0 && i < N && j >= 0 && j < N;
    }

    public double knightProbability(int N, int K, int r, int c) {
        double[][][] mem = new double[102][32][32];
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < N; ++j) {
                mem[0][i][j] = 1;
            }
        }

        for (int k = 1; k <= K; ++k) {
            for (int i = 0; i < N; ++i) {
                for (int j = 0; j < N; ++j) {
                    for (int[] d : dir) {
                        int nx = i + d[0];
                        int ny = j + d[1];
                        if (check(nx, ny, N)) {
                            mem[k][i][j] += 1 / 8.0 * mem[k - 1][nx][ny];
                        }
                    }
                }
            }
        }
        return mem[K][r][c];
    }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏数据结构与算法

cf914D. Bash and a Tough Math Puzzle(线段树)

可以这么想,如果能成功的话,我们可以把那个数改成$1$,这样比$x$大的数就不会对答案产生影响了。

601
来自专栏数据结构与算法

HDU6315 Naive Operations(线段树 复杂度分析)

设\(d_i\)表示\(i\)号节点还需要加\(d_i\)次才能产生\(1\)的贡献

624
来自专栏小樱的经验随笔

Codeforces Round #415 (Div. 2)(A,暴力,B,贪心,排序)

A. Straight «A» time limit per test:1 second memory limit per test:256 megabytes...

3259
来自专栏计算机视觉与深度学习基础

Leetcode 162 Find Peak Element

A peak element is an element that is greater than its neighbors. Given an inpu...

1927
来自专栏杨建荣的学习笔记

oracle坏块修复实例

最近几天发现库里有坏块了,环境是11gR2, linux平台的64位的库。以下是我的修复办法,基于dbms_repair做的在线修复,也可以基于备份rman来修...

3249
来自专栏杨建荣的学习笔记

用shell脚本巧妙统计文件(r2笔记57天)

在数据迁移的过程中,会产生大量的dump文件,需要对dump的文件情况进行一个简单清晰的管理,比如目录下的文件特别多,而且某些表比较大,对应的dump文件比较多...

2316
来自专栏算法修养

PAT 1004 Counting Leaves

1004. Counting Leaves (30) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B ...

3628
来自专栏ml

HDUOJ------1711Number Sequence

Number Sequence Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/3...

2766
来自专栏小樱的经验随笔

Codeforces Round #395 (Div. 2)(A.思维,B,水)

A. Taymyr is calling you time limit per test:1 second memory limit per test:256 ...

2776
来自专栏ACM小冰成长之路

51Nod-1443-路径和树

ACM模版 描述 ? 题解 这个题是单源最短路 + 最小生成树。 首先我们来介绍一下题中所述的最短路径树是什么,我们都知道,给定一个 uu 求单源最短路时,所有...

17710

扫码关注云+社区