迷宫
题目要求
P1605题目链接
我的思路还比较容易理解,但确实开的数组太多了(最终代码)。 我想开一个递归的DFS搜索,对越界情况进行淘汰 (话说这能算剪枝吗) ,再就是只允许在没被标记为已遍历的地方行进。 DFS用好了确实能搜出结果,但过程中遇到过一个大问题,下面就对此说明。
原先的代码是这样的:
import java.util.Scanner;
public class Main {
private static int x1, y1, x2, y2;
private static int dfs(int x, int y, boolean[][] graph) {
if (x x2 || y y2 || graph[x][y]) {
return 0;
} else if (x == x2 && y == y2) {
return 1;
}
graph[x][y] = true;
return dfs(x-1, y, graph) + dfs(x+1, y, graph) + dfs(x, y-1, graph) + dfs(x, y+1, graph);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt(), n = scanner.nextInt(), num = scanner.nextInt();
x1 = scanner.nextInt();
y1 = scanner.nextInt();
x2 = scanner.nextInt();
y2 = scanner.nextInt();
boolean[][] graph = new boolean[m+1][n+1];
for (int i = 0; i
关注
打赏
热门博文
- 【Linux】Ubuntu20.04安装和卸载MySQL8
- 【Linux】Ubuntu 20.04 报错 curl: (23) Failure writing output to destination 的解决方法
- 【Java】JUnit 4.13.2 警告 ‘assertEquals(double, double)‘ is deprecated 的解决方法
- 【JavaScript】处理 @parcel/transformer-js: Browser scripts cannot have imports or exports.
- 【Node.js】Windows环境安装配置NVM和Node.js
- 【Python】处理TypeError: Plain typing.NoReturn is not valid as type argument
- 【Python】Matplotlib可视化50例
- 【C语言】C语言修改MySQL数据库
- 【Java】从默认包导入类和对象报错的解决方法
- 【Java】panel.getGraphics()报错空指针异常的解决方法