【剑指 offer】机器人的运动范围

题目描述:

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

思路:

dfs回溯。

代码:

class Solution {
    int dir[4][2] = { {1,0}, {-1,0}, {0,1}, {0,-1} };
    int step[1010][1010];
    int vis[1010][1010];

public:
    int movingCount(int threshold, int rows, int cols) {
        if (threshold < 0) return 0;
        memset(vis, -1, sizeof(vis));
        memset(step, -1, sizeof(step));

        vis[0][0] = 1;
        int ans = dfs(0, 0, rows, cols, threshold);
        return ans;
    }

    int dfs(int stx, int sty, int rows, int cols, int threshold) {
        if (step[stx][sty] != -1) return step[stx][sty];
        int ans = 0;
        for (int i=0; i<4; ++i) {
            int x = stx + dir[i][0];
            int y = sty + dir[i][1];
            if (x < 0 || x >= rows || y < 0 || y >= cols)
                continue;
            if (vis[x][y] == 1) continue;
            if (!judge(x, y, threshold)) continue;
            vis[x][y] = 1;
            ans += dfs(x, y, rows, cols, threshold);
        }
        ans += 1;
        step[stx][sty] = ans;
        return ans;
    }

    bool judge(int x, int y, int threshold) {
        int tot = 0;
        while(x) {
            tot += x % 10;
            x /= 10;
        }
        while(y) {
            tot += y % 10;
            y /= 10;
        }
        if (tot <= threshold) return true;
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/88358435