问题描述
我正试图在迷宫中找到所有唯一有效的行进路线(“ H”)或下降(“ V”)的路径。我想返回这些路径的字符串列表。
我的代码当前不返回这些字符串的列表,我认为错误在于尝试使用相同的String对象以递归方式构建答案。如果有人可以帮助我解决该问题(或他们可能看到的其他错误),我将不胜感激!
我考虑过参加协调员课程,这是正确的方法吗?如果是这样,我不确定如何使用此类制作正确的字符串。我以为这堂课看起来像这样:
public static class Coordinate {
public int row,col;
public String path;
public Coordinate (int row,int col) {
this.row = row;
this.col = col;
path = new String();
}
public addLetter(String s) {
path = path + s;
}
}
如果我的矩阵的尺寸为3:这个问题的例子:
0 1 2
0 X H H
1 V
2 V
0 1 2
0 X H
1 V H
2 V
0 1 2
0 X H
1 V
2 V H
0 1 2
0 X
1 V H H
2 V
0 1 2
0 X
1 V H
2 V H
0 1 2
0 X
1 V
2 V H H
And all the possible strings are:
- HHVV,HVHV,HVVH,VHHV,VHVH,VVHH
因此,如果输入n等于3,则该函数应返回字符串列表[“ HHVV”,“ HVHV”,“ HVVH”,“ VHHV”,“ VHVH”,“ VVHH”]。
如果输入n为2,则函数应返回: [“ HV”,“ VH”]。
class Result {
public static List<String> getSafePaths(int n) {
//do a dfs on the graph
List<String> paths = new ArrayList<>();
int er = n - 1;
int ec = n - 1;
int[][] matrix = new int[n][n];
matrix[0][0] = 2; //all visited nodes changed to two
getPaths(matrix,er,ec,paths,"");
return paths;
}
public static void getPaths(int[][] matrix,int sr,int sc,int er,int ec,List<String> paths,String s) {
if(sr == er && sc == ec) {
paths.add(new String(s));
}
final int[][] SHIFTS = {
{0,1},//go right
{1,0} // go down
};
for(int[] shift : SHIFTS) {
int right = -1;
int down = -1;
//are we going down or right? Need this to add correct letter
if(shift[0] == 0) {
right = 1;
}
else {
down = 1;
}
String letter = valid(matrix,sr + shift[0],sc + shift[1],right,down);
if(letter != null) {
if(letter == "H") {
s = s + "H";
}
if(letter == "V") {
s = s + "V";
}
matrix[sr + shift[0]][sc + shift[1]] = 2;
getPaths(matrix,s);
}
}
}
public static String valid(int[][] matrix,int right,int down) {
if(sr >= 0 && sr < matrix.length && sc >= 0 && sc < matrix[sr].length && matrix[sr][sc] != 2) {
if(right == 1) {
return "H";
}
else {
return "V";
}
}
return null;
}
}
解决方法
主要问题(但不一定唯一)是标记访问位置(通过将matrix
的值设置为2来标记)。
用2标记位置后,以下搜索将无法在路径中包括该位置。
例如,考虑目标位置。到达后,将其标记为2,这意味着无法再进行后续搜索。这就是为什么paths
仅在搜索完成后仅包含一个路径的原因。
实际上,在这种情况下,根本不需要标记访问位置。唯一可能的移动是向下和向右移动,因此搜索不能两次返回相同位置。
只需注释掉matrix[currentRow + shift[0]][currentColumn + shift[1]] = 2;
即可获得更多路径(并显示更多错误)。
边注:
/* check for equality between strings by letter.equals("H")
if(letter == "H") {
s = s + "H";
}
if(letter == "V") {
s = s + "V";
}
*/
//the two if blocks are not needed. letter can only be V or H so simply do:
s=s+letter; //or s+=letter or s=s.concat(letter)