天天看點

面試題67. 機器人的運動範圍

題目描述

地上有一個m行和n列的方格。一個機器人從坐标0,0的格子開始移動,每一次隻能向左,右,上,下四個方向移動一格,但是不能進入行坐标和列坐标的數位之和大于k的格子。

例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8

= 19。請問該機器人能夠達到多少個格子?

public class Solution
    public int movingCount(int threshold, int rows, int cols) {
        boolean[] visited = new boolean[rows * cols];
        return movingCountCore(threshold, rows, cols, 0, 0, visited);
    }

    public int movingCountCore(int threshold, int rows, int cols, 
                               int row, int col, boolean[] visited) {
        int count = 0;

        // 檢查能否進入方格
        if(check(threshold, rows, cols, row, col, visited)) {
            visited[row * cols + col] = true;
            count = 1 + movingCountCore(threshold, rows, cols, row - 1, col, visited) 
                + movingCountCore(threshold, rows, cols, row + 1, col, visited) 
                + movingCountCore(threshold, rows, cols, row, col - 1, visited) 
                + movingCountCore(threshold, rows, cols, row, col + 1, visited);

        }        
        return count;
    }

    public boolean check(int threshold, int rows, int cols, 
                               int row, int col, boolean[] visited) {
        return (row >=0 
            && row < rows 
            && col >=0 
            && col < cols
            && (!visited[row * cols + col])
            && (getDigitSum(row) + getDigitSum(col) <= threshold)
        );
    }

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