在程序设计中,关于迷宫的问题,有书中提到迷宫的最短路径问题,并给出了相关C代码,思考良久,利用宽度优先算法怎么可以得到最短路径,百思不得解,将C代码改写java代码后经测试发现,的确不能得到最短路径,充其量也只能得到其中的一条路径。现将代码献上。
public class ShortestPath {
private static char[][] path = new char[][]{
{'#','S','#','#', '#', '#', '#', '#', '.','#'},
{'.','.','.','.', '.', '.', '#', '.', '.','#'},
{'.','#','.','#', '#', '.', '#', '#', '.','#'},
{'.','#','.','.', '.', '.', '.', '.', '.','.'},
{'#','#','.','#', '#', '.', '#', '#', '#','#'},
{'.','.','.','.', '#', '.', '.', '.', '.','#'},
{'.','#','.','#', '#', '#', '#', '#', '.','#'},
{'.','.','.','.', '#', '.', '.', '.', '.','.'},
{'.','#','.','#', '#', '.', '#', '#', '#','.'},
{'.','.','.','.', '.', '.', '.', '.', 'G','#'}
};
private static int sx, sy;
private static int gx = 9, gy = 8;
static int dx[] = {1,0,-1,0}; static int dy[] = {0,1,0,-1};
private static int d[][] = new int[path.length][path[0].length];
public static void main(String argsp[]) {
int res = bfs();
for(int i = 0 ; i< d.length ; i++) {
System.out.println(Arrays.toString(d[i]));
}
System.out.println(res);
}
private static int bfs() {
sx = 0; sy = 1;
for(int i= 0; i < path.length; i++) {
for(int j = 0; j < path[0].length; j++) {
d[i][j] = 0;
}
}
d[sx][sy] = 1;
Deque<Point> queue = new ArrayDeque<>();
queue.push(new Point(sx,sy));
while(!queue.isEmpty()) {
Point p = queue.pop();
if(p.getX() == gx && p.getY() == gy) {
break;
}
for(int i = 0; i<4; i++) {
int nx = p.getX() + dx[i], ny = p.getY() + dy[i];
if(0 <= nx && nx < path.length && 0 <= ny && ny < path[0].length && path[nx][ny] != '#' && d[nx][ny] == 0) {
queue.push(new Point(nx, ny));
d[nx][ny] = d[p.getX()][p.getY()] + 1;
}
}
}
return d[gx][gy];
}
static class Point{
private int x;
private int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
}