**《剑指offer》66:机器人运动范围(回溯法)

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

C++实现:

class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        bool *flag = new bool[rows*cols];
        for(int i = 0; i < rows * cols; i ++)
            flag[i] = false;
        
        int r = 0;
        r = move(threshold, 0, 0, rows, cols, flag);

        return r;
    }
    
    int move(int ts, int x, int y, int m, int n, bool *f)
    {
        int c = 0;
        if(check(ts, x, y, m, n, f))
        {
            f[x + y * n] = true;
            c = 1 + move(ts, x + 1, y, m, n, f) + move(ts, x, y + 1, m, n, f) + move(ts, x - 1, y, m, n, f) + move(ts, x, y - 1, m, n, f);
        }
        return c;
    }
    
    bool check(int ts, int x, int y, int m, int n, bool *f)
    {
        if(num(ts, x, y) && (x < n) && (y < m) && (x >= 0) && (y >= 0) && f[x + y * n] == false)
        {
            return true;
        }
        return false;
    }
    
    bool num(int ts, int x, int y)
    {
        int sum = 0, t = 0;
        while(x)
        {
            t = x % 10;
            sum = sum + t;
            x = x / 10;
        }
        
        while(y)
        {
            t = y % 10;
            sum = sum + t;
            y = y / 10;
        }
        
        if(sum <= ts)
            return true;
        else
            return false;
    }
};

猜你喜欢

转载自blog.csdn.net/w113691/article/details/81174322
今日推荐