机器人的运动范围
* 题目:地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,
* 它每次可以向左,右,上,下移动一格,但不能进入行坐标和列坐标的数位之和
* 大于k的格子,例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7=18。
* 但它不能进入方格(35,38),因为3+5+3+8=19.请问该机器人能够到达多少个格子?
package com.cloud.algorithm.demo;
import jdk.nashorn.internal.parser.JSONParser;
import org.junit.Test;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* DATE: 2021/4/8
* Author: xiaoqu
* Version: 1.0.0
*/
public class Topic13 {
/**
* 机器人的运动范围
* 题目:地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,
* 它每次可以向左,右,上,下移动一格,但不能进入行坐标和列坐标的数位之和
* 大于k的格子,例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7=18。
* 但它不能进入方格(35,38),因为3+5+3+8=19.请问该机器人能够到达多少个格子?
*/
@Test
public void topic13_1() {
Map map = new HashMap();
int i = this.demo01(4, 100, 100, 0, 0, map, 0);
System.out.println(i);
System.out.println(map.toString());
}
public int demo01(int sum, int rows, int cols, int row, int col, Map dataMap, int count) {
int i = this.sum(row) + this.sum(col);
int key = row * cols + col;
String haveRead = (String) dataMap.get(key);
if (col < 0 || row < 0 || col > cols - 1 || row > rows - 1 || i > sum || !StringUtils.isEmpty(haveRead)) {
return count;
}
if (i <= sum) {
dataMap.put(key, row + "," + col);
count++;
int top = this.demo01(sum, rows, cols, row - 1, col, dataMap, count);
int down = this.demo01(sum, rows, cols, row + 1, col, dataMap, top);
int left = this.demo01(sum, rows, cols, row, col - 1, dataMap, down);
int right = this.demo01(sum, rows, cols, row, col + 1, dataMap, left);
count = right;
}
return count;
}
public int sum(int i) {
int sum = 0;
while (true) {
int i1 = i / 10;
sum += i % 10;
i = i1;
if (i == 0) {
break;
}
}
return sum;
}
}