Range of motion of the robot to prove safety offer13

Range of motion of the robot to prove safety offer13
Here Insert Picture Description

class Solution {
public:
    int getSingleSum(int x){
        int s=0;
        while(x){
            s+=x%10;
            x/=10;
        }
        return s;
    }
    int getSum(pair<int,int> p){
        return getSingleSum(p.first)+getSingleSum(p.second);
    }
    int movingCount(int m, int n, int k) {
        //比较大的范围用宽度优先遍历,不用深度优先遍历,否则会栈溢出
        int res=0;
        if(!m||!n) return 0;

        vector<vector<bool>> st(m,vector<bool>(n));         //判重矩阵
        queue<pair<int,int>> q;         //宽搜队列

        int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
        q.push({0,0});
        while(q.size()){
            auto t = q.front();
            q.pop();

            if(getSum(t)>k||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<m && y>=0 && y<n)
                q.push(make_pair(x,y));            
            }
        }
        return res;
    }
};

Algorithm thinking: This is a classic problem of BFS, the time complexity is O (m * n), which is the number of elements, because you want to traverse all the elements. Overall, the idea of ​​solving a wide search is to define a queue, and then entered into the queue element, it is determined that while (q.size ()), there is a queue element to continue the cycle, and then find the point of not traversed , added to the queue. Similar ideas have binary tree traversal level, on issues related to the binary tree, I can refer to another blog, on DFS and BFS topic LeetCode in, you can refer to my blog.

Published 28 original articles · won praise 34 · views 2670

Guess you like

Origin blog.csdn.net/weixin_44289697/article/details/104720341