题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:
使用一个与矩阵等大小的布尔数组防止重复计算。用两个栈记录坐标,最后返回栈大小即为运动范围
package jianzhioffer;
import java.util.Stack;
public class MS13 {
public static void main(String[] args) {
int k = 18;
int m = 5;
int n = 5;
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
boolean[][] array = new boolean[m][n];
stack1.push(0);
stack2.push(0);
array[0][0] = true;
robot(k,stack1,stack2,array);
System.out.println(stack1.size());
while(!stack1.isEmpty()){
System.out.println("("+stack1.pop()+","+stack2.pop()+")");
}
}
public static void robot(int k,Stack<Integer> stack1,Stack<Integer> stack2,boolean[][] array){
int i = stack1.peek();
int j = stack2.peek();
//向上找
if (i>0&&!array[i-1][j]){
array[i-1][j] = true;
int numer = count(i-1,j);
if (numer<=k) {
stack1.push(i - 1);
stack2.push(j);
robot(k, stack1, stack2, array);
}
}
//向下找
if (i<array.length-1&&!array[i+1][j]){
array[i+1][j] = true;
int numer = count(i+1,j);
if (numer<=k){
stack1.push(i+1);
stack2.push(j);
robot(k, stack1, stack2, array);
}
}
//向左找
if (j>0&&!array[i][j-1]){
array[i][j-1] = true;
int numer = count(i,j-1);
if (numer<=k){
stack1.push(i);
stack2.push(j-1);
robot(k, stack1, stack2, array);
}
}
//向右找
if (j<array[0].length-1&&!array[i][j+1]){
array[i][j+1] = true;
int numer = count(i,j+1);
if (numer<=k){
stack1.push(i);
stack2.push(j+1);
robot(k, stack1, stack2, array);}
}
}
public static int count(int i,int j){
int res = 0;
while (i!=0){
res = res+i%10;
i=i/10;
}
while (j!=0){
res = res+j%10;
j=j/10;
}
return res;
}
}