recursion - 如果存在解决方案,迷宫问题的复杂性(应用回溯算法)
问题描述
这是解决方案:使用递归树方法,看起来它应该是指数的,即 4 次幂 n。但解决它并不清楚。就像人们在采访中的描述一样。任何帮助表示赞赏。
class Solution {
public static boolean hasPath(int[][] maze, int[] start, int[] destination) {
boolean result = false;
result = moveNext(maze, start[0], start[1], destination);
return result;
}
public static boolean moveNext(int[][] graph, int i, int j, int[] destination) {
if (i < 0 || i == graph.length ||
j < 0 || j == graph[0].length ||
graph[i][j] == 1)
return false;
graph[i][j] = 1;
if (i == destination[0] && j == destination[1])
return true;
return moveNext(graph, i, j + 1, destination)
|| moveNext(graph, i + 1, j, destination)
|| moveNext(graph, i, j - 1, destination)
|| moveNext(graph, i - 1, j, destination);
}
public static void main(String args[]) {
int[][] maze = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 0, 1, 1 },
{ 0, 0, 0, 0 }
};
int start[] = { 0, 0 };
int destination[] = { 3, 3 };
System.out.println(hasPath(maze, start, destination));
}
}
解决方案
推荐阅读
- node.js - 如何将 HTTP POST 请求从 localhost 发送到运行在 AWS EC2 实例上的 nodemailer
- spring - Java Spring JPA 转换为 myBatis
- java - 如何将java输出解析为CSV文件
- html - 当子 div 具有特定的 className 时如何向父 div 添加样式
- loops - 将函数应用于拆分数据集
- python - 如何在 Python 中重新评估变量的值?
- r - 如何在数据框中有效地存储来自变量和因子水平的不同组合的计算?
- flutter - 我想从 FireStore 获取字段数据
- google-chrome - 在某些情况下,inspect.exe 无法在 chrome 或 cef 页面中获得 AutomationId?
- python - 如何在数据框熊猫中反转范围值