我需要在(0,0)到(N,N)的N * N矩阵迷宫中找到最短路径,假设1是可通过的,0不是,3是目的地,使用记忆来缓存结果。以下是我的解决方案,可以正确找到最短的路径。
但是缓存无法正常工作。它只存储它找到的第一条路径。我该如何解决这个问题?
public static class MazeResult {
public boolean solved;
public List<String> res = new ArrayList<String>();
public int steps = Integer.MAX_VALUE;
public MazeResult(boolean isSolved) {
solved = isSolved;
}
}
static Map<String, MazeResult> cache = new HashMap<String, MazeResult>();
public static MazeResult solveMaze(int[][] m, int r, int c, List<String> path, HashSet<String> visited) {
if (r < 0 || r >= m.length || c < 0 || c >= m[0].length)
return new MazeResult(false);
String cell = r + "" + c + "";
if (m[r][c]==0 || visited.contains(cell))
return new MazeResult(false);
if (m[r][c] == 3) {
MazeResult ret = new MazeResult(true);
ret.res = new ArrayList<String>(path);
ret.res.add(cell);
ret.steps = path.size() + 1;
return ret;
}
if (cache.containsKey(cell))
return cache.get(cell);
path.add(cell);
visited.add(cell);
MazeResult ret = new MazeResult(false), temp = new MazeResult(false);
temp = solveMaze(m, r, c+1, path, visited);
compareResult(temp, ret);
temp = solveMaze(m, r, c-1, path, visited);
compareResult(temp, ret);
temp = solveMaze(m, r+1, c, path, visited);
compareResult(temp, ret);
temp = solveMaze(m, r-1, c, path, visited);
compareResult(temp, ret);
path.remove(path.size()-1);
visited.remove(cell);
cache.put(cell, ret);
return ret;
}
private static void compareResult(MazeResult temp, MazeResult ret) {
if (temp.solved) {
if (temp.steps < ret.steps) {
ret.res = temp.res;
ret.steps = temp.steps;
}
ret.solved = true;
}
}
答案 0 :(得分:0)
没关系。我已经弄清楚了。我应该在向结果列表中添加单元格时使用自下而上的方法,而不是使用自上而下的方法。