题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
题目链接:
package com.sunshine.OFFER66_SECOND; import org.junit.Test; public class A66_movingCount { @Test public void test() { int i = movingCount(10, 1, 100); System.out.println(i); } int rows; int cols; int threshold; int ans = 0; public int movingCount(int threshold, int rows, int cols) { boolean[] flags = new boolean[rows * cols]; this.rows=rows; this.cols=cols; this.threshold=threshold; BFS(flags, 0, 0); return ans; } private void BFS(boolean[] flags, int x, int y) { if (!check(flags, x, y)) { return; } int curSum = 0; int tx = x; while (tx > 0) { curSum += tx % 10; tx /= 10; } int ty = y; while (ty > 0) { curSum += ty % 10; ty /= 10; } if(curSum>threshold){ return; } flags[x * cols + y] = true; ans++; BFS(flags, x + 1, y); BFS(flags, x - 1, y); BFS(flags, x, y + 1); BFS(flags, x, y - 1); return; } private boolean check(boolean[] flags, int x, int y) { if (x >= 0 && x < rows && y >= 0 && y < cols && !flags[x * cols + y]) { return true; } return false; } }