java - 回溯问题,我不知道我的解决方案是否正确
问题描述
我正在练习回溯问题,这是问题描述: https ://practiceit.cs.washington.edu/problem/view/cs2/sections/recursivebacktracking/travel
编写一个 travel 方法,它接受整数 x 和 y 作为参数,并使用递归回溯通过重复使用三个移动之一来打印在二维平面中从 (0, 0) 到 (x, y) 的所有解决方案:
东(E):右移 1(增加 x) 北(N):上移 1(增加 y) 东北(NE):上移 1 和右 1(增加 x 和 y)。
这是我得到的:我让它在一条路径上工作,但我不确定如何让它去探索所有其他可能的路径。我认为我的基本案例设计是错误的,但我不确定。我只想知道我应该首先解决什么,是基本情况还是我的整个概念是错误的。
public class PracticeRecordCode {
public static void main(String[] args) {
travel(1, 2);
}
public static String travel(int x, int y){
List<String> allpath = new ArrayList<String>();
String eachpath = "";
return explore(0, 0, x, y, eachpath, allpath);
}
public static String explore(int x, int y, int des_x, int dest_y, String eachPath, List<String> allpath) {
//Base case
if(x == des_x && y== dest_y) {
String result = "";
if(isRepeated(eachPath, allpath)){
allpath.add(eachPath);
eachPath = "";
}
// Print all content from allpath
for (String path : allpath) {
result += path + "\n";
System.out.println(path);
}
return result;
} else {
if(x == des_x && y != dest_y){
eachPath += "N ";
if(!allpath.contains(eachPath)) {
allpath.add(eachPath);
}
explore(x, y+1, des_x, dest_y, eachPath, allpath);
} else if(x != des_x && y == dest_y) {
eachPath += "E ";
allpath.add(eachPath);
explore(x + 1, y, des_x, dest_y, eachPath, allpath);
} else {
eachPath += "NE ";
allpath.add(eachPath);
explore(x + 1, y+1, des_x, dest_y, eachPath, allpath);
}
}
return "";
}
// Check if this path has been done already
public static boolean isRepeated(String path, List<String> allpath){
return allpath.contains(path);
}
}
解决方案
你可以试试我的代码。希望它可以为您提供解决方案->
public static void main(String[] args) {
baktracking(new boolean[5][3], 0, 0, 2, 2, "");
}
static void baktracking(boolean m[][], int x, int y, int dx, int dy, String ans) {
if (x == dx && y == dy) {
System.out.println(ans);
return;
}
if (x < 0 || y < 0 || x >= m.length || y >= m[0].length) {
return;
}
m[x][y] = true;
baktracking(m, x, y +1, dx, dy, ans + "E" + " ");
baktracking(m, x + 1, y, dx, dy, ans + "N" + " ");
baktracking(m, x + 1, y + 1, dx, dy, ans + "NE" + " ");
m[x][y] = false;
}
推荐阅读
- javascript - 使用 vanilla js 禁用/重新启用表单元素 - 无法正常工作
- php - 嵌入 youtube 视频时没有“访问控制允许来源”错误
- java - 如何从字符串数组中获取随机字符串
- sas - SAS - 选择第一次出现唯一 ID 的行(ID 可以在两列中)
- html - bootstrap 4 datetimepicker如何本地化
- flutter - Flutter:尝试从图库或相机中选择图像时,Image_Picker 使应用程序崩溃
- sql-server - EF Core:包含导致左连接具有不可为空的外键
- react-native - React Native 切换按钮和同时更改主题
- c# - 如何从 HttpPostedFile InputStream 属性中读取正确的 Stream/byte[]?
- sql - 如何比较Oracle中不同表中的日期