• 从(0,0)点开始判断是否在范围内;
  • 判断条件:行和列数位之和<=阈值;
  • 如果超出范围,当前位置已访问,超出阈值,返回0;
  • 设置当前位置已访问,向下向右依次验证,记录可到达的格子;
  • 返回最终结果。
class Solution {
public:
    bool canReach(int i, int j, int threshold) {
        int sum = 0;
        while (i > 0) {
            sum += i % 10;
            i /= 10;
        }
        while (j > 0) {
            sum += j % 10;
            j /= 10;
        }
        return sum <= threshold;
    }
    int moveRegion(int threshold, vector<vector<bool>>& visited, int i, int j, int rows, int cols) {
        if (i >= rows || j >= cols || visited[i][j] || !canReach(i, j, threshold)) {
            return 0;
        }
        visited[i][j] = true;
        return moveRegion(threshold, visited, i + 1, j, rows, cols) + moveRegion(threshold, visited, i, j + 1, rows, cols) + 1;
    }
    int movingCount(int threshold, int rows, int cols) {
        vector<vector<bool>> visited(rows, vector<bool>(cols, false));
        return moveRegion(threshold, visited, 0, 0, rows, cols);
    }
};