剑指offer--48.机器人的运动范围

这道题不是要求走一趟最多走多少,而是最多走多少,WA几次才想通。
--------------------------------------------------------------------------------------------------------------------
时间限制:1秒 空间限制:32768K 热度指数:142006

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
class Solution {
    public:
        int movingCount(int threshold, int rows, int cols) {
            if(threshold<0) return 0;
            row = rows;
            col = cols;
            ct= 1 ;
            memset(ma, 0, sizeof(ma));
            ma[0][0] = 1;
            dfs(threshold,0,0);
            return ct;
        }
        void dfs(int k, int rr ,int cc) {
            for(int i=0; i<4; i++) {
                int c = dir[i][0] + cc;
                int r = dir[i][1] + rr;
                if(ma[r][c]==1 || c <0 || r<0 || c>=col || r>=row || sum_n(c, r) > k) continue;
                ma[r][c] = 1;
                ++ct; 
                dfs(k, r, c);
            }
        }
        int sum_n(int a, int b) {
            int sumab = 0;
            while (a != 0) {
                sumab += a%10;;
                a /= 10;
            }
            while (b != 0) {
                sumab += b%10;;
                b /= 10;
            }
            return sumab;
        }
    private:
        int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
        int ma[80][80];
        int row, col, ct;
};
原文地址:https://www.cnblogs.com/slothrbk/p/10631653.html