前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Sword To Offer 066 - 机器人的运动范围

Sword To Offer 066 - 机器人的运动范围

作者头像
Reck Zhang
发布2021-08-11 11:44:39
2750
发布2021-08-11 11:44:39
举报
文章被收录于专栏:Reck Zhang

机器人的运动范围

Desicription

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

Solution

代码语言:javascript
复制
class Solution {
private:
    int count = 0;
    int row = 0;
    int col = 0;
    int limit = 0;
    vector<vector<int>> dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    vector<vector<bool>> visit;
    void onSearch(int x, int y) {
        int tempX = x;
        int tempY = y;
        int total = 0;
        while(tempX) {
            total += tempX % 10;
            tempX /= 10;
        }
        while(tempY) {
            total += tempY % 10;
            tempY /= 10;
        }
        if(total > limit) {
            return ;
        }
        visit[x][y] = true;
        count++;
        for(int i = 0; i < 4; i++) {
            int dx = x + dir[i][0];
            int dy = y + dir[i][1];
            if(dx < 0 || dx >= row || dy < 0 || dy >= col || visit[dx][dy]) {
                continue;
            }
            onSearch(dx, dy);
        }
    }
public:
    int movingCount(int threshold, int rows, int cols) {
        limit = threshold;
        row = rows;
        col = cols;
        visit = vector<vector<bool>>(row, vector<bool>(col,false));
        onSearch(0, 0);
        return count;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-05-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 机器人的运动范围
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档