牛客(66)机器人的运动范围

//    题目描述
//    地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
//    每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
//    例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。
//    但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

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

        boolean[] isVisited = new boolean[rows * cols];
        int[] spots = {0};

        doHasPath(rows, cols, 0, 0, isVisited, spots, threshold);
        return spots[0];
    }

    public void doHasPath(int rows, int cols, int row, int col, boolean[] isVisited, int[] pathLength,
                          int threshold) {

        if (row >= 0 && col >= 0 && row < rows && col < cols && !isVisited[row * cols + col]) {
            if (toSum(row)+toSum(col)<=threshold){
                pathLength[0]++;
                isVisited[row * cols + col] = true;
                doHasPath(rows, cols, row, col + 1, isVisited, pathLength, threshold);
                doHasPath(rows, cols, row + 1, col, isVisited, pathLength, threshold);
                doHasPath(rows, cols, row, col - 1, isVisited, pathLength, threshold);
                doHasPath(rows, cols, row - 1, col, isVisited, pathLength, threshold);
            }
            isVisited[row * cols + col] = true;
        }
        return;
    }

    public static int toSum(int num){
        int sum=0;
        String sNum = ""+num;
        String[] chars = sNum.split("");
        for (int i=0;i<chars.length;i++){
            sum += new Integer(chars[i]);
        }
        return sum;
    }

猜你喜欢

转载自www.cnblogs.com/kaibing/p/9138940.html