题目主要考察深度优先和广度优先搜索算法,核心为根据一个二维数组来保存查找状态(是否已被遍历过),再根据x,y未超过m,n、没有被遍历过、各位数和不超过k来做边界条件,最后要注意加上自己(0,0)题目 力扣https://leetcode.cn/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/
package leetcode.May;
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;
/**
* @description:
* @author: qiangyuecheng
* @date: 2022/5/18 15:33
*/
public class Robots {
public int get(int i, int j) {
int res = 0;
while (i + j > 0) {
res += i % 10 + j % 10;
i /= 10;
j /= 10;
}
return res;
}
/**
* 广度优先搜索 BFS
*/
public int BFS(int m, int n, int k) {
int res = 1;
Queue<int[]> queue = new ArrayDeque();
int[][] status = new int[m][n];
queue.offer(new int[]{0, 0});
//向右移动
int[] tx = {1, 0};
//想下移动
int[] ty = {0, 1};
while (!queue.isEmpty()) {
int[] tmp = queue.poll();
int x = tmp[0];
int y = tmp[1];
for (int i = 0; i <= 1; i++) {
int tmpx = x + tx[i];
int tmpy = y + ty[i];
if (tmpx >= m || tmpy >= n || status[tmpx][tmpy] != 0 || get(tmpx, tmpy) > k) {
continue;
} else {
status[tmpx][tmpy] = 1;
res += 1;
queue.offer(new int[]{tmpx, tmpy});
}
}
}
return res;
}
/**
* 深度优先搜索 DFS
*/
static int[] tx = new int[]{1, 0};
static int[] ty = new int[]{0, 1};
public int DFS(int m, int n, int k) {
int[][] source = new int[m][n];
return toDFS(source, 0, 0,m,n, k)+1;
}
public int toDFS(int[][] sou, int x, int y, int m, int n, int k) {
if (x >= m || y >= n || get(x, y) > k||sou[x][y]==1) {
return 0;
}
sou[x][y]=1;
int res = 0;
for (int i = 0; i < 2; i++) {
res+=toDFS(sou,x+tx[i],y+ty[i],m,n,k);
}
return res+1;
}
public static void main(String[] args) {
Robots robots = new Robots();
System.out.println(robots.BFS(1, 2, 1));
System.out.println(robots.DFS(1, 2, 1));
}
}