剑指offer:13.机器人的运动范围

13-机器人的运动范围

来源:力扣(LeetCode)

链接: https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/

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

示例 1:

输入:m = 2, n = 3, k = 1
输出:3

示例 2:

输入:m = 3, n = 1, k = 0
输出:1

提示:

  • 1 <= n,m <= 100
  • 0 <= k <= 20

解法

回溯法:由于机器人能上下左右运动,因此只要满足要求的不能进入行坐标和列坐标的数位之和大于k的格子,即可继续往下走动,因此,可以用一个栈存储运动的点,每次弹出栈的元素,然后从该点向四周发散的找,新的点再入栈。

代码实现

  • python实现, 二维标记是否被访问过
class Solution:
    def movingCount(self, m: int, n: int, k: int) -> int:
        def get(x):
            ans = 0
            while x:
                ans += x % 10
                x = x // 10
            return ans
        
        map_grid = [[0]*n for _ in range(m)]
        stack = []
        stack.append((0, 0))
        res = 0
        map_grid[0][0] = 1  # 标记已经访问过了
        while stack:
            x, y = stack.pop()
            res += 1
            for del_x, del_y in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                new_x = x + del_x
                new_y = y + del_y
                if new_x < 0 or new_x >=m or new_y < 0 or new_y >= n or get(new_x)+get(new_y) > k or map_grid[new_x][new_y] == 1:
                    continue
                else:
                    stack.append((new_x, new_y))
                    map_grid[new_x][new_y] = 1
        return res
  • c++实现
class Solution {

public:
    int get(int x) {
        int res=0;
        for (; x; x /= 10) {
            res += x % 10;
        }
        return res;
    }

    int movingCount(int m, int n, int k) {
        if (!k) return 1;
        queue<pair<int,int> > Q;
        // 向右和向下的方向数组,原因是其它方向可以通过一步完成
        int dx[2] = {0, 1};
        int dy[2] = {1, 0};
        vector<vector<int> > vis(m, vector<int>(n, 0));
        Q.push(make_pair(0, 0));
        vis[0][0] = 1;
        int ans = 1;
        while (!Q.empty()) {
            auto [x, y] = Q.front();
            Q.pop();
            for (int i = 0; i < 2; ++i) {
                int tx = dx[i] + x;
                int ty = dy[i] + y;
                if (tx < 0 || tx >= m || ty < 0 || ty >= n || vis[tx][ty] || get(tx) + get(ty) > k) continue;
                Q.push(make_pair(tx, ty));
                vis[tx][ty] = 1;
                ans++;
            }
        }
        return ans;
    }
};

复杂度分析

  • 时间复杂度: O ( M N ) O(MN) O(MN),遍历矩阵M,N
  • 空间复杂度: O ( M N ) O(MN) O(MN),二维数组表示是否遍历

你可能感兴趣的:(#,编程练习-剑指offer,广度优先遍历,二维数组,上下左右)