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

剑指offer_25_机器人的运动范围

作者头像
用户6055494
发布2019-11-07 14:43:35
3030
发布2019-11-07 14:43:35
举报
文章被收录于专栏:AVAJAVAJ
描述:地上有m行n列的方格,一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标大于K的格子。例如,当k为15时,机器人能够进入(33,45),因为3+3+4+5=15,但是它不能进入方格(33,46),因为3+3+4+6=16,。请问该机器人能够到达多少个格子?

解析:采用回溯法,定义一个数组来记录机器人所到过的位置,防止重复计算,然后分别向四个方向移动,判断是否能到达。

代码如下:

代码语言:javascript
复制
public int movingCount(int threshold,int rows ,int cols) {
    boolean[] visted = new boolean[rows * cols];
    for (int i = 0; i < visted.length; i++) {
        // 用这个数组来判断机器人是否经过了某个位置
        visted[i] = false;
    }
    // 获取机器人最多可到达的位置
    int count = movingCountCore(threshold,rows,cols,0,0,visted);
    return count;
}

private int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visted) {
    int count = 0;
    if (check(threshold,rows,cols,row,col,visted)) {
        // 判断符合条件后,将该位置标记为已经来过
        visted[rows * cols + col] = true; // 代表访问过了的
        // 向上下左右四个位置探索
        count = 1 +
                movingCountCore(threshold, rows , cols, row - 1, col, visted) +
                movingCountCore(threshold, rows, cols, row, col - 1, visted) +
                movingCountCore(threshold, rows, cols, row + 1, col, visted) +
                movingCountCore(threshold, rows, cols, row, col + 1, visted);
    }
    return count;
}

private boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visted) {
    // 判断是否越界啦 判断和是否大于阀值
    if (row >=0 && row < rows && col >= 0 && col < cols &&  (getDigitSum(row) + getDigitSum(col) <= threshold) && !visted[row * cols + col])
        return true;
    return false;
}
// 求坐标的和
private int getDigitSum(int row) {
    int sum = 0;
    while (row > 0) {
        sum += row % 10;
        row /= 10;
    }
    return sum;
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-10-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员面试鸭 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档