一、題目描述
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
二、代碼實現
寬搜法:
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
private final int[] dx = {-1, 1, 0, 0};
private final int[] dy = {0, 0, -1, 1};
private static boolean[][] states = null;
public int movingCount(int threshold, int rows, int cols)
{
if (threshold < 0) {
return 0;
}
int ret = 0;
states = new boolean[rows][cols];
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(0, 0));
states[0][0] = true;
while (!queue.isEmpty()) {
//Point top = queue.remove();
Point top = queue.poll();
int x = top.getX();
int y = top.getY();
ret++;
for (int i=0; i<4; i++) {
int X = x + dx[i];
int Y = y + dy[i];
if (X>=0 && Y>=0 && X<rows && Y<cols && states[X][Y]==false &&
bitsSum(X, Y) <= threshold) {
states[X][Y] = true;
queue.add(new Point(X, Y));
}
}
}
return ret;
}
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public int bitsSum(int x, int y) {
int result = 0;
while (x > 0) {
result += x % 10;
x = x / 10;
}
while (y > 0) {
result += y % 10;
y = y / 10;
}
return result;
}
}
深搜法:
public class Solution {
private final int[] dx = {-1, 1, 0, 0};
private final int[] dy = {0, 0, -1, 1};
private static boolean[][] states = null;
private static int count = 0;
public int movingCount(int threshold, int rows, int cols)
{
if (threshold < 0) {
return 0;
}
states = new boolean[rows][cols];
states[0][0] = true;
count = 1;
backtracking(0, 0, rows, cols, threshold);
return count;
}
public void backtracking(int x, int y, int m, int n, int threshold) {
for (int k=0; k<4; k++) {
int X = x + dx[k];
int Y = y + dy[k];
if (X>=0 && Y>=0 && X<m && Y<n && states[X][Y]==false && bitsSum(X,Y)<=threshold) {
count++;
states[X][Y] = true;
backtracking(X, Y, m, n, threshold);
}
}
}
public int bitsSum(int x, int y) {
int result = 0;
while (x > 0) {
result += x % 10;
x = x / 10;
}
while (y > 0) {
result += y % 10;
y = y / 10;
}
return result;
}
}