Leetcode Interview Question 13. The range of motion of the robot [simple search BFS or DFS]

Problem Description

There is a grid with m rows and n columns on the ground, from coordinates [0,0] to coordinates [m-1, n-1]. A robot is easy to understand from the grid of coordinates [0,0], it can move one grid to the left, right, up, and down at a time (it cannot move outside the grid), nor can it enter the sum of row and column coordinates greater than k Of each. For example, when k is 18, the robot can enter the square [35,37] because 3 + 5 + 3 = 7 = 18. But it cannot enter the square [35,38] because 3 + 5 + 3 + 8 = 19. How many grids can the robot reach?

Problem solving report

Just search directly, BFS or DFS

Implementation code

class Solution {
public:
    int sum(int x){
        int ans=0;
        while(x){
            ans+=(x%10);
            x=x/10;
        }
        return ans;
    }
    int movingCount(int m, int n, int k) {
        int ans=0,qnum,ox,oy,nx,ny;
        int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
        vector<bool>vis(m*n,false); 
        queue<int>q;
        q.push(0);
        vis[0]=true;
        while(!q.empty()){
            qnum=q.front();
            q.pop();
            ans++;
            ox=qnum/n;
            oy=qnum%n;
            for(int index=0;index<4;index++){
                nx=ox+dx[index];
                ny=oy+dy[index];
                if(nx>=0&&nx<m&&ny>=0&&ny<n&&!vis[n*nx+ny]&&
                			sum(nx)+sum(ny)<=k){
                    q.push(n*nx+ny);
                    vis[n*nx+ny]=true;
                }
            }
        }
        return ans;
    }
};

References

[1] Leetcode Interview Question 13. The range of motion of the robot

MD_
Published 139 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_27690765/article/details/105381659