Range of motion of the robot's offer to prove safety

Title Description

A ground grid and m rows n columns. A robot moves from the grid coordinates 0,0, every time only left, right, upper, lower four directions a cell, but can not enter the row and column coordinates of the grid is greater than the sum of the number of bits k. For example, when k is 18, the robot can enter the box (35, 37), because 3 + 3 + 5 + 7 = 18. However, it can not enter the box (35, 38), because 3 + 3 + 5 + 8 = 19. Will the robot be able to reach the number of lattice?

Thinking

From (0,0) to start walking, every successful step by marking the current position is true, then explore from the current position to the four directions. Exploring, it determines whether the current node is reachable criteria:
1) the current node in the matrix;
2) the current node has not been accessed;
3) satisfies the current node limit restriction.
If unreachable, mark the corresponding flag is true, count ++

Code

class Solution {
public:
    int count= 0;
    int movingCount(int threshold, int rows, int cols)
    {
        if(threshold < 1 || rows < 1 || cols <1)
            return 0;
        bool *flag=new bool[rows*cols];
        memset(flag,false,rows*cols);
        move_on(threshold,rows,cols,0,0,flag);
        return count;
    }
    void move_on(int threshold, int rows, int cols, int P_x, int P_y, bool* flag)
    {
        int index = P_x * cols + P_y;
        int condition = cal(P_x,P_y);
        if(P_x < 0 || P_x > rows-1 || P_y < 0 || P_y > cols-1 || condition > threshold || flag[index] == true)
            return;
        flag[index] = true;
        count++;
        move_on(threshold,rows,cols,P_x+1,P_y,flag);
        move_on(threshold,rows,cols,P_x,P_y+1,flag);
        move_on(threshold,rows,cols,P_x-1,P_y,flag);
        move_on(threshold,rows,cols,P_x,P_y-1,flag);
        return;
    }
    int cal(int x, int y)
    {
        int res = 0;
        string s_x,s_y,s;
        s_x = to_string(x);
        s_y = to_string(y);
        s = s_x + s_y;
        for(int i = 0; i < s.size();i++)
        {
            res = res + s[i]-'0';
        }
        return res;
    }
};
Published 85 original articles · won praise 0 · Views 389

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104888089
Recommended