we can do some improvements to your explore
method, as there is some defect in your implementation. There are two exit conditions: 1. when you reach the destination, which is a valid path and we can save it into your final result. 2. you reach over the destination (x>des_x || y>dest_y)
, which means that's an invalid path, and we don't have to keep exploring any more. And otherwise, you have 3 options to keep exploring: E, N, or NE. And as each direction is unique, you don't have to worry about duplicate.
when all possible explore is done, your allpath
list will have all the valid paths added. And you can either return the list or print it.
Based on this, your code can be much simpler like this:
import java.util.ArrayList;
import java.util.List;
public class PracticeRecordCode {
public static void main(String[] args) {
travel(2, 2);
}
public static void travel(int x, int y){
List<String> allpath = new ArrayList<String>();
explore(0, 0, x, y, "", allpath);
// Print all content from allpath
for (String path : allpath) {
System.out.println(path);
}
}
public static void 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) {
allpath.add(eachPath);
return;
}
if(x>des_x || y>dest_y)
return;
explore(x + 1, y, des_x, dest_y, eachPath + "E ", allpath);
explore(x, y+1, des_x, dest_y, eachPath + "N ", allpath);
explore(x + 1, y+1, des_x, dest_y, eachPath + "NE ", allpath);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…