13:机器人的运动范围

有一个m行n列的方格,一个机器人从坐标(0 ,0) 的格子开始移动,它每次可以向上下左右移动一格,但不能进入坐标位数和大于threshold的格子,求机器人一共能到达多少个格子

机器人从(0, 0)开始移动,当要移动到(i, j) 时,先判断i, j是否满足条件,如果满足,就进入,递归执行。如果不满足,尝试其他相邻的格子。 需要一个辅助数组visited[][] 来记录移动的踪迹

public static int movingCount(int threshold, int rows, int cols) {
    if (rows < 0 || cols < 0 || threshold < 0) return 0;

    boolean[][] visited = new boolean[rows][cols];
    int count = movingCountCore(threshold, 0, 0, rows, cols, visited);

    return count;
}

public static int movingCountCore(int threshold, int row, int col, int rows, int cols, boolean[][] visited) {
    if (row >= 0 && row < rows && col >= 0 && col < cols &&
        getDigitSum(row) + getDigitSum(col) <= threshold &&
        !visited[row][col]
       ) {
        visited[row][col] = true;
        return 1 + movingCountCore(threshold, row - 1, col, rows, cols, visited) +
            movingCountCore(threshold, row + 1, col, rows, cols, visited) +
            movingCountCore(threshold, row, col - 1, rows, cols, visited) +
            movingCountCore(threshold, row, col + 1, rows, cols, visited);
    }

    return 0;
}

public static int getDigitSum(int num) {
    int sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

猜你喜欢

转载自blog.csdn.net/weixin_41889284/article/details/89222179