剑指offer系列——66.机器人的运动范围

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

    int movingCount(int threshold, int rows, int cols) {
        bool *array = new bool[rows * cols];
        for (int i = 0; i < rows * cols; i++)
            array[i] = true;
        //从起点开始即可
        return getCount(threshold, 0, 0, rows, cols, array);
    }

    int getCount(int threshold, int i, int j, int rows, int cols, bool *array) {
        int index = i * cols + j;
        if (i < 0 || j < 0 || i >= rows || j >= cols || !array[index] || addSum(i) + addSum(j) > threshold)
            return 0;
        //走过就不会再经过了
        array[index] = false;
        return 1 + getCount(threshold, i - 1, j, rows, cols, array) + getCount(threshold, i + 1, j, rows, cols, array) +
               getCount(threshold, i, j - 1, rows, cols, array) + getCount(threshold, i, j + 1, rows, cols, array);
    }

    int addSum(int i) {
        int sum = 0;
        while (i) {
            sum += i % 10;
            i = i / 10;
        }
        return sum;
    }
posted @ 2020-03-01 18:13  Shaw_喆宇  阅读(87)  评论(0编辑  收藏  举报