问题描述:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),
因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
每来到一个新的且满足条件的格子时,计数加一,除矩阵的边界,任意一个方格都有四个方向可以选择,但是一个到过的格子不能进入两次,所以要对访问过的数据进行标记
首先在核心方法(movingCount)中进行形参是否满足条件的检测 三个形参
声明一个布尔类型的数组可以表示对数据是否访问过的标记
返回下一个函数 move 六个形参
move中首先声明一个计数器
如果找到元素(check方法 六个形参)
标记已经进行访问的数据 进行递归搜索返回计数器
package com.helan.b;
public class RobotMove {
public static int movingCount(int k,int row,int col){
if(k<0||row<=0||col<=0){
return 0;
}
boolean mark[]=new boolean[row*col];
for(int i=0;i<row*col;i++){
mark[i]=false;
}
return move(k,row,col,mark,0,0);
}
private static int move(int k, int rows, int cols, boolean[] mark, int r, int c) {
int count = 0;
if (check(k, rows, cols, mark, r, c)) {
mark[r * cols + c] = true;
count = move(k, rows, cols, mark, r-1, c)+
move(k, rows, cols, mark, r+1, c)+
move(k, rows, cols, mark, r, c-1)+
move(k, rows, cols, mark, r, c+1)+1;
}
return count;
}
private static boolean check(int k, int rows, int cols, boolean[] mark, int r, int c) {
return r<rows&&c<cols&&r>=0&&c>=0&&!mark[r * cols + c]&&digitSum(r)+digitSum(c)<=k;
}
private static int digitSum(int num) {
int sum=0;
while (num>0){
sum=sum+num%10;
num=num/10;
}
return sum;
}
static void test(String testName, int threshold, int rows, int cols, int expected) {
if (testName != null) {
System.out.print(testName + ":");
}
if (movingCount(threshold, rows, cols) == expected) {
System.out.println("通过.");
}else {
System.out.println("失败.");
}
}
// 方格多行多列
static void test1() {
test("Test1", 5, 10, 10, 21);
}
// 方格多行多列
static void test2() {
test("Test2", 15, 20, 20, 359);
}
// 方格只有一行,机器人只能到达部分方格
static void test3() {
test("Test3", 10, 1, 100, 29);
}
// 方格只有一行,机器人能到达所有方格
static void test4() {
test("Test4", 10, 1, 10, 10);
}
// 方格只有一列,机器人只能到达部分方格
static void test5() {
test("Test5", 15, 100, 1, 79);
}
// 方格只有一列,机器人能到达所有方格
static void test6() {
test("Test6", 15, 10, 1, 10);
}
// 方格只有一行一列
static void test7() {
test("Test7", 15, 1, 1, 1);
}
// 方格只有一行一列
static void test8() {
test("Test8", 0, 1, 1, 1);
}
// 机器人不能进入任意一个方格
static void test9() {
test("Test9", -10, 10, 10, 0);
}
public static void main(String[] args) {
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
}
}