class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if (threshold < 1)
            return 0;
        set<pair<int, int>> res;
        set<pair<int, int>> trash;
        res.insert(make_pair(0, 0));

        find(make_pair(0, 0), res, trash, threshold, rows, cols);
        return res.size();
    }

    // 迭代函数是探索当前节点的上下左右节点是否走过
    void find(pair<int, int> cur, set<pair<int, int>> &res, set<pair<int, int>> &trash, int threshold, int rows, int cols){

        // 右探索
        pair<int, int> right = make_pair(cur.first+1, cur.second);
        if(res.find(right) == res.end() && trash.find(right) == trash.end() && right.first < cols){
            auto num = method(right.first, right.second);
            if (num <= threshold){
                res.insert(right);
                find(right, res, trash, threshold, rows, cols);
            }
            else
                trash.insert(right);
        }

        // 左探索
        pair<int, int> left = make_pair(cur.first-1, cur.second);
        if(res.find(left) == res.end() && trash.find(left) == trash.end() && left.first >= 0){
            auto num = method(left.first, left.second);
            if (num <= threshold){
                res.insert(left);
                find(left, res, trash, threshold, rows, cols);
            }
            else
                trash.insert(left);
        }

        // 上探索
        pair<int, int> up = make_pair(cur.first, cur.second-1);
        if(res.find(up) == res.end() && trash.find(up) == trash.end() && up.second >= 0){
            auto num = method(up.first, up.second);
            if (num <= threshold){
                res.insert(up);
                find(up, res, trash, threshold, rows, cols);
            }
            else
                trash.insert(up);
        }

        // 下探索
        pair<int, int> down = make_pair(cur.first, cur.second+1);
        if(res.find(down) == res.end() && trash.find(down) == trash.end() && down.second < rows){
            auto num = method(down.first, down.second);
            if (num <= threshold){
                res.insert(down);
                find(down, res, trash, threshold, rows, cols);
            }
            else
                trash.insert(down);
        }
    }

    //求两个正整数各位之和
    int method(int a, int b){
        int res = 0;
        while (a > 9){
            res += a % 10;
            a /= 10;
        }
        res += a;
        while (b > 9){
            res += b % 10;
            b /= 10;
        }
        res += b;
        return res;
    }
};

刚开始天真的认为若一个格子不可行,则它的下边格子和右边格子也都不可行,在此假设下不可行域是规则形状,绞尽脑汁想出计算公式----部分案例过不去,该方法流产。
然后老实用回溯法试探搜索
1、用递归的思想探索当前格子的上下左右格子,用两个set分别记录走过的可行格子和走过的不可行格子
2、对一个格子值计算前先满足(1)没走过(2)没越界
3、最后用公式计算就可以了
ps:原本想着用stack记录探索路径,后来发现递归法没有那个必要
欢迎交流指正!!!