剑指OFFER笔记_13_机器人的运动范围_JAVA实现
题目:机器人的运动范围
- 地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。请问该机器人能够到达多少个格子?
解题思路
- 此题与前一题类似,采用回溯法。
- 对(0,0)时的情况开始调用函数计算count,当此处的条件符合时,依次递归调用row±1和col±1的情况,如果不符合条件,就返回前一次的情况。
- 需要一个check函数,去检测当前的坐标的数位之和是否<=k。
- 需要一个visited数组去记录当前坐标的方格是否已经被计算过了,避免重复的情况。
- 值得注意的是,我在Solution的代码中一开始将count设置成static类型的了,单次用例的时候没有问题,但是当LeetCode进行多次测试的时候,就会将每次的结果累加起来,从而产生错误。
代码
函数主体部分代码
package q13;
public class Solution {
//记录可以到达的点的个数
// public static int count = 0;
public int count = 0;
public int movingCount(int m, int n, int k) {
if (m <= 0 || n <= 0 || k < 0)
{
return 0;
}
int row = 0;
int col = 0;
boolean visited[][] = new boolean[m][n];
for (int i = 0; i < visited.length; i++) {
for (int j = 0; j < visited[0].length; j++) {
visited[i][j] = false;
}
}
// System.out.println("count is : " + count);
CalculateCount(row, col, k, m, n, visited);
return count;
}
/**
* 计算有多少可到达点。
* @param row 当前行号
* @param col 当前列号
* @param k k的设置
* @param m 行号上限
* @param n 列号上限
*/
public void CalculateCount(int row, int col, int k, int m, int n, boolean[][] visited)
{
if (row >=0 && col >= 0 && row <= m-1 && col <= n-1 && check(row, col, k) && !visited[row][col])
{
this.count++;
System.out.println("row:" + row + ", col:" + col);
System.out.println("count is : " + count);
visited[row][col] = true;
CalculateCount(row+1, col, k, m, n, visited);
CalculateCount(row-1, col, k, m, n, visited);
CalculateCount(row, col+1, k, m, n, visited);
CalculateCount(row, col-1, k, m, n, visited);
}
}
public boolean check(int row, int col, int k)
{
int result = 0;
while(row > 0)
{
result += row % 10;
row /= 10;
}
while(col > 0)
{
result += col % 10;
col /= 10;
}
if (result <= k)
{
return true;
}else
{
return false;
}
}
}
测试部分代码
package q13;
public class TestApp {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.movingCount(8,7 ,3));
}
}
运行结果截图
LeetCode运行截图