题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
BFS
代码实现
/**
* @Classname Solution
* @Description BFS
* @Date 2019/12/29 22:39
* @Author SonnSei
*/
public class Solution {
static int[][] moves = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
public int movingCount(int threshold, int rows, int cols) {
int count = 0;
int[][] map = new int[rows][cols];
int[][] visited = new int[rows][cols];
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0, 0});
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
if (!inArea(x, y, map)||visited[x][y] == 1) continue;
visited[x][y] = 1;
if (!check(x, y, threshold)) continue;
count++;
for (int[] move : moves) {
queue.add(new int[]{cur[0] + move[0], cur[1] + move[1]});
}
}
return count ;
}
private boolean check(int x, int y, int threshold) {
int ret = 0;
while (x != 0 || y != 0) {
ret += x % 10;
ret += y % 10;
y = y / 10;
x = x / 10;
}
return ret <= threshold;
}
boolean inArea(int x, int y, int[][] map) {
if (x < 0 || x >= map.length) return false;
if (y < 0 || y >= map[0].length) return false;
return true;
}
}
复杂度分析
- 时间复杂度: O ( m × n ) {O(m\times n)} O(m×n)
- 空间复杂度: O ( m × n ) {O(m\times n)} O(m×n)
DFS
代码实现
/**
* @Classname Solution2
* @Description DFS
* @Date 2019/12/29 23:10
* @Author SonnSei
*/
public class Solution2 {
static int[][] moves = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
static int count = 0;
public int movingCount(int threshold, int rows, int cols)
{
count = 0;
int[][] map = new int[rows][cols];
int[][] visited = new int[rows][cols];
dfs(map, visited, 0, 0, threshold);
return count;
}
private void dfs(int[][] map, int[][] visited, int x, int y, int threshold) {
// 主要要先判断xy是否合法,否则下面的判断会越界
if(!inArea(x,y,map))return;
if(visited[x][y]==1)return;
if(!check(x,y,threshold))return;
visited[x][y] = 1;
count++;
for (int[] move : moves) {
dfs(map,visited,x+move[0],y+move[1],threshold);
}
}
boolean inArea(int x, int y, int[][] map) {
if (x < 0 || x >= map.length) return false;
if (y < 0 || y >= map[0].length) return false;
return true;
}
private boolean check(int x, int y, int threshold) {
int ret = 0;
while (x != 0 || y != 0) {
ret += x % 10;
ret += y % 10;
y = y / 10;
x = x / 10;
}
return ret <= threshold;
}
}
复杂度分析
- 时间复杂度: O ( m × n ) {O(m\times n)} O(m×n)
- 空间复杂度: O ( m × n ) {O(m\times n)} O(m×n)