剑指Offer面试题13:机器人的运动范围 Java实现

来源:互联网 发布:mac os x 10.13.1 cdr 编辑:程序博客网 时间:2024/06/06 23:54

剑指Offer 面试题13:机器人的运动范围

原题描述:

面试题13:机器人的运动范围

地上有一个m行n列的方格,机器人从坐标(0,0)的各自开始移动,每次可以往上下左右移动一格,但不能进入行列坐标的数位之和大于k的格子。问机器人能够达到多少个格子。


这题还是用回溯法解决问题,直接上Java代码了!


/** * @param threshold 行列坐标的数位之和限制 * @param rows 方格行数 * @param cols 方格列数 * @return 能够到达的格子数 */public static int movingCount(int threshold, int rows, int cols) {if (threshold < 0 || rows <= 0 || cols <= 0) {return 0;}boolean[] visited = new boolean[rows * cols];int count = movingCountCore(threshold, rows, cols, 0, 0, visited);return count;}

/** * @param threshold * @param rows * @param cols * @param row 准备进入的格子行坐标 * @param col 准备进入的格子列坐标 * @param visited 标记每个格子是否已经记录过 * @return */private static int movingCountCore(int threshold, int rows, int cols, int row, int col, boolean[] visited) {int count = 0;if (check(threshold, rows, cols, row, col, visited)) {visited[row * cols + col] = true;count = 1 + movingCountCore(threshold, rows, cols, row - 1, col, visited)+ movingCountCore(threshold, rows, cols, row, col - 1, visited)+ movingCountCore(threshold, rows, cols, row + 1, col, visited)+ movingCountCore(threshold, rows, cols, row, col + 1, visited);}return count;}

//判断这个方格是否满足访问条件private static boolean check(int threshold, int rows, int cols, int row, int col, boolean[] visited) {if (row >= 0 && row < rows && col >= 0 && col < cols && getDigitSum(row) + getDigitSum(col) <= threshold&& !visited[row * cols + col])return true;return false;}


//计算下标各位数和private static int getDigitSum(int number) {int sum = 0;while (number > 0) {sum += number % 10;number /= 10;}return sum;}
测试代码如下:

public static void main(String[] args) {int [] kArr={0,1,2,3,4};int [] result=new int[kArr.length];for(int i=0;i<kArr.length;i++){result[i]=movingCount(kArr[i],3,6);}String s=Arrays.toString(result);System.out.println(s);}

输出结果为:[1, 3, 6, 9, 12]

做了Offer上两道回溯法的题目,但对这个概念还是有点蒙。立个flag,这个周末专门捋一下这个思想。

原创粉丝点击