思路:

宽度优先搜索

确定起点坐标后,向四周进行搜索

在节点扩展时需要判断是否重复,是否出边界,横纵坐标数字之和小于K

 

代码:

class Solution {
public:
    //坐标进行计算
    int single_sum(int x)
    {
        int s=0;
        while(x) s+=x%10,x/=10;
        return s;
    }
    int get_sum(pair<int,int>p)
    {
        return single_sum(p.first) + single_sum(p.second);
    }
    int movingCount(int threshold, int rows, int cols)
    {
        int res=0;
        //判断为空条件
        if(!rows || !cols) return 0;
        
        //判断矩阵中搜索重复问题
        vector<vector<bool>> st(rows,vector<bool>(cols));
        //将矩阵的坐标看成是一个点放入队列中
        queue<pair<int,int>> q;
        
        q.push({0,0});
        
        int dx[4]={-1,0,1,0}, dy[4]={0,-1,0,1};
        while(q.size())
        {
            auto t=q.front();
            q.pop();
            
            //判断边界条件
            if(get_sum(t)> threshold ||st[t.first][t.second]) continue;
            res ++;
            //对走过的点进行标记
            st[t.first][t.second] = true;
            
            //机器人移动
            for(int i=0;i<4;i++)
            {
                int x=t.first + dx[i], y=t.second+dy[i];
                //判断
                if(x>=0 && x<rows && y>=0 && y<cols) q.push({x,y})
            }
        }
        return res;
    }
};