迷路の最短経路アルゴリズムを成功裏に完成させました (以下のコードを参照)。ただし、関数に渡される Stack パラメーターに最短パスの座標を格納したいと考えています。どうすればこれを達成できるか教えてください。ここに私が取り組んでいる迷路があります:
凡例: 1: 壁、0: 有効なパス、s: 開始、e: 終了
String[][] map = new String[][]
{
new String[] { "1","1","1","0","0","0","1","1","1","1" },
new String[] { "s","0","0","0","1","1","0","0","0","1" },
new String[] { "1","1","0","0","1","0","0","1","0","1" },
new String[] { "1","1","1","0","0","0","0","0","0","1" },
new String[] { "1","0","1","1","1","0","1","1","0","1" },
new String[] { "0","0","0","0","0","0","0","0","0","1" },
new String[] { "0","1","1","1","1","1","1","1","1","1" },
new String[] { "0","0","0","0","0","0","0","0","0","e" },
};
私のアルゴリズム:
// Pre-condition: Two integers indicating the row and col number to start from,
// a 2d array of string objects representing the map of the maze,
// a 2d array of booleans mapping out the visited cells in the maze
// A string array containing the map of the maze.
// An empty Stack object
// Post-conditon: The distance of the shortest path from the current cell(start)
// to the end of the maze
public static int shortestPath(int row,int col,boolean[][] visited,String[][] map,Stack<Pair> path)
{
if(row < 0 || row >= map.length || col < 0 || col >= map[0].length)
return -1;
else if(visited[row][col] == true)
return -1;
else if(map[row][col].equals("e"))
return 0;
else
{
// Mark the current cell as visited
visited[row][col] = true;
// There is a wall
if(map[row][col].equals("1"))
return -1;
else
{
int[] pathDist = new int[4];
// Start finding the path from the left
int left = 1 + shortestPath(row,col-1,visited,map,path);
// Start searching from the right
int right = 1 + shortestPath(row,col+1,visited,map,path);
// Start searching from the bottom
int down = 1 + shortestPath(row+1,col,visited,map,path);
// Start searching from the top
int up = 1 + shortestPath(row-1,col,visited,map,path);
visited[row][col] = false;
pathDist[0] = left;
pathDist[1] = right;
pathDist[2] = down;
pathDist[3] = up;
Arrays.sort(pathDist);
for(Integer i : pathDist)
if(i > 0) return i;
return -1;
}
}
}
}