关于java:JZ066机器人的运动范围

6次阅读

共计 1750 个字符,预计需要花费 5 分钟才能阅读完成。

机器人的静止范畴

题目形容

地上有一个 m 行和 n 列的方格。一个机器人从坐标 0,0 的格子开始挪动,每一次只能向左,右,上,下四个方向挪动一格,然而不能进入行坐标和列坐标的数位之和大于 k 的格子。例如,当 k 为 18 时,机器人可能进入方格(35,37),因为 3 +5+3+7 = 18。然而,它不能进入方格(35,38),因为 3 +5+3+8 = 19。

  • 请问该机器人可能达到多少个格子?

题目链接 : 机器人的静止范畴

代码

/**
 * 题目:机器人的静止范畴
 * 题目形容
 * 地上有一个 m 行和 n 列的方格。一个机器人从坐标 0,0 的格子开始挪动,每一次只能向左,右,上,下四个方向挪动一格,然而不能进入行坐标和列坐标的数位
 * 之和大于 k 的格子。例如,当 k 为 18 时,机器人可能进入方格(35,37),因为 3 +5+3+7 = 18。然而,它不能进入方格(35,38),因为 3 +5+3+8 = 19。* 请问该机器人可能达到多少个格子?* 题目链接:* https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&&tqId=11219&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz66 {private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    private int cnt = 0;
    private int rows;
    private int cols;
    private int threshold;
    private int[][] digitSum;

    /**
     * 深度优先搜寻(Depth First Search,DFS)* 回溯是深度优先搜寻的一种特例,它在一次搜寻过程中须要设置一些本次搜寻过程的部分状态,并在本次搜寻完结之后革除状态。* 而一般的深度优先搜寻并不需要应用这些部分状态,尽管还是有可能设置一些全局状态。*
     * @param threshold
     * @param rows
     * @param cols
     * @return
     */
    public int movingCount(int threshold, int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.threshold = threshold;
        initDigitSum();
        boolean[][] marked = new boolean[rows][cols];
        dfs(marked, 0, 0);
        return cnt;
    }

    private void dfs(boolean[][] marked, int r, int c) {if (r < 0 || r >= rows || c < 0 || c >= cols || marked[r]) {return;}
        marked[r] = true;
        if (this.digitSum[r] > this.threshold) {return;}
        cnt++;
        for (int[] n : next) {dfs(marked, r + n[0], c + n[1]);
        }
    }

    private void initDigitSum() {int[] digitSumOne = new int[Math.max(rows, cols)];
        for (int i = 0; i < digitSumOne.length; i++) {
            int n = i;
            while (n > 0) {digitSumOne[i] += n % 10;
                n /= 10;
            }
        }
        this.digitSum = new int[rows][cols];
        for (int i = 0; i < this.rows; i++) {for (int j = 0; j < this.cols; j++) {this.digitSum[i][j] = digitSumOne[i] + digitSumOne[j];
            }
        }
    }

    public static void main(String[] args) {Jz66 jz66 = new Jz66();
        int i = jz66.movingCount(18, 20, 20);
        System.out.println(i);
        System.out.println(4 / 10);
    }
}

【每日寄语】人之初,性本善;性相近,习相远。

正文完
 0