66.机器人的运动范围

题目描述

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


思路一(DFS):

采用深度优先遍历,只从(0, 0)处开始,函数中传入int &res 用来记录结果,代码如下。


代码一:

class Solution {
public:
    int getnum(int i, int j) {
        int cnt = 0;
        while(i != 0) {
            cnt += i % 10;
            i /= 10;
        }
        while(j != 0) {
            cnt += j % 10;
            j /= 10;
        }
        return cnt;
    }
    void dfs(int threshold, int row, int col, int rows, int cols, vector<vector<bool>> &check, int& res) {
        if(row >= 0 && row < rows && col >= 0 && col < cols && !check[row][col] && getnum(row, col) <= threshold) {
            ++res;
            check[row][col] = true;
            dfs(threshold, row + 1, col, rows, cols, check, res);
            dfs(threshold, row - 1, col, rows, cols, check, res);
            dfs(threshold, row, col + 1, rows, cols, check, res);
            dfs(threshold, row, col - 1, rows, cols, check, res);
        }
    }
    int movingCount(int threshold, int rows, int cols) {
        int res = 0;
        vector<vector<bool>> check(rows, vector<bool>(cols, false));
        dfs(threshold, 0, 0, rows, cols, check, res);
        return res;
    }
};


思路二(BFS):

广度优先遍历,同样从原点(0,0)出发,在将原点入栈前需要检查原点是否满足条件,若满足则入栈,并++res和重新设定标志位;随后采用while(!q.empty())的标准格式进行广度优先遍历,遍历完后res即为最终结果。

巧妙的定义int getnum(int i, int j){...} 函数,可以使代码更清晰,也更便于程序的书写。


代码二:

扫描二维码关注公众号,回复: 2415067 查看本文章
class Solution {
public:
    int getnum(int i, int j) {
        int cnt = 0;
        while(i != 0) {
            cnt += i % 10;
            i /= 10;
        }
        while(j != 0) {
            cnt += j % 10;
            j /= 10;
        }
        return cnt;
    }
    int movingCount(int threshold, int rows, int cols) {
        int res = 0;
        vector<vector<bool>> check(rows, vector<bool>(cols, false));
        int dx[4] = {0, 0, 1, -1};
        int dy[4] = {1, -1, 0, 0};
        queue<pair<int, int>> q;
        if(0 <= threshold) {
            check[0][0] = true;
            ++res;
            q.push(pair<int, int>(0, 0));
        }
        while(!q.empty()) {
            auto pos = q.front();
            q.pop();
            int x = pos.first;
            int y = pos.second;
            for(int i = 0; i < 4; ++i) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if(nx >=0 && nx < rows && ny >= 0 && ny < cols &&
                   !check[nx][ny] && getnum(nx, ny) <= threshold) {
                    check[nx][ny] = true;
                    ++res;
                    q.push(pair<int, int>(nx, ny));
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/nichchen/article/details/80652778