矩阵问题 | 机器人的运动范围

2019-08-03  本文已影响0人  icebreakeros

机器人的运动范围

地上有一个mn列的方格,一个机器人从坐标(0,0)的格子开始移动,它每一次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子

分析
机器人从坐标(0,0)开始移动,当它准备进入坐标为(i,j)的格子时,通过检查坐标的数位和来判断机器人是否能够进入,如果能够进入,则继续判断是否能够进入四个相邻的格子

public class RobotMove {

    public int movingCount(int threshold, int rows, int columns) {
        if (threshold < 0 || rows <= 0 || columns <= 0) {
            return 0;
        }

        boolean[][] visited = new boolean[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                visited[i][j] = false;
            }
        }
        
        int count = movingCountCore(threshold, rows, columns, 0, 0, visited);
        print(visited);
        return count;
    }

    private int movingCountCore(int threshold, int rows, int columns,
                                int row, int column, boolean[][] visited) {
        int count = 0;
        if (check(threshold, rows, columns, row, column, visited)) {
            visited[row][column] = true;
            count = 1 + movingCountCore(threshold, rows, columns, 
                         row, column - 1, visited)
                    + movingCountCore(threshold, rows, columns, 
                         row, column + 1, visited)
                    + movingCountCore(threshold, rows, columns, 
                         row - 1, column, visited)
                    + movingCountCore(threshold, rows, columns, 
                         row + 1, column, visited);
        }
        return count;
    }

    private boolean check(int threshold, int rows, int columns,
                          int row, int column, boolean[][] visited) {
        if (row >= 0 && row < rows && column >= 0 && column < columns
                && getDigit(row) + getDigit(column) <= threshold 
                && !visited[row][column]) {
            return true;
        }
        return false;
    }

    private int getDigit(int number) {
        int sum = 0;
        while (number > 0) {
            sum += number % 10;
            number /= 10;
        }
        return sum;
    }

    private void print(boolean[][] visited) {
        for (int i = 0; i < visited.length; i++) {
            for (int j = 0; j < visited[0].length; j++) {
                System.out.printf("%b\t", visited[i][j]);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        RobotMove robotMove = new RobotMove();
        int result = robotMove.movingCount(5, 10, 10);
        System.out.println(result);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读