【剑指offer】面试题13:机器人的运动范围——回溯法

【剑指offer】面试题13:机器人的运动范围——回溯法_第1张图片

方法一:回溯法

参考12题的思路https://blog.csdn.net/weixin_45566765/article/details/107875499
1.我们创建一个二维数组flag记录每个当前的坐标是否走过;
2.通过movingCount_recursion往所有的点进行回溯查找;
3.检查当前的坐标点是否符合要求([1]所有的位数和小于、[2]坐标不超过边界、[3]flag为0没有走过)

class Solution {
public:
    int movingCount(int m, int n, int k) {
        if( k < 0 || n <=0 || n > 100 || m <=0 || m > 100)
            return 0;

        rows = m;
        cols = n;

        vector<vector<int> > flag(rows, vector<int>(cols, 0));

        int count = movingCount_recursion(0, 0, rows, cols, k, flag);
        
        return count;
    }

private:
    int movingCount_recursion(int row,int col, int rows, int cols,int k, vector<vector<int> > &flag)
    {
        int count = 0;
        if( check_coordinate(row,col, rows, cols, k, flag) )
        {
            flag[row][col] = 1;
            count = 1 + movingCount_recursion( row + 1, col, rows, cols, k, flag )
                      + movingCount_recursion( row - 1, col, rows, cols, k, flag )
                      + movingCount_recursion( row, col + 1, rows, cols, k, flag )
                      + movingCount_recursion( row, col - 1, rows, cols, k, flag );
        }
        return count;
    }

    bool check_coordinate(int row,int col, int rows, int cols,int k,vector<vector<int> > &flag)
    {
        if( row >= 0 && row <= rows - 1 && col >=0 && col <= cols - 1 
            && getDigitSum(row) + getDigitSum(col) <= k  && flag[row][col] == 0 )
        {
            return true;
        }
        return false;
    }

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

        return sum;
    } 

    int rows,cols;
};

你可能感兴趣的:(数据结构与算法,算法,数据结构)