【发布时间】:2021-01-22 20:34:19
【问题描述】:
我正在练习回溯问题,这是问题描述: 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);
}
}
【问题讨论】:
标签: java recursive-backtracking