原题链接:迷宫中离入口最近的出口
这是一道经典的迷宫题,也是经典的最短路径。
通常我们最短路径,会使用bfs,也就是深度优先遍历来使用,当然也不排除使用动态规划等。
实现深度优先遍历,首先是要使用队列,因为队列具有先进先出的性质,这可以使从一个点开始,往外扩散,依次遍历。
不多说,代码附上
class Solution {
int[] station_x = {1,0,-1,0};
int[] station_y = {0,-1,0,1};
Queue<Pos> que = new LinkedList();
int N = 105;
char[][] a ;
public int nearestExit(char[][] maze, int[] entrance) {
a = maze;
bfs(entrance[0],entrance[1]);
if(q == Integer.MAX_VALUE) return -1;
else
return q;
}
int q = Integer.MAX_VALUE;
public void bfs(int x,int y) {
que.add(new Pos(x,y,0));
a[x][y] = '+';
int tx,ty,tstep;
int step = 0;
//如果队列非空
while(!que.isEmpty()) {
//将当前的点取出来,然后运算,求出周围四个点
x = que.peek().x;
y = que.peek().y;
step = que.peek().step;
que.poll();
for(int i = 0; i < 4;i++) {
tx = x + station_x[i];
ty = y + station_y[i];
tstep = step + 1;
if(tx < 0 || ty < 0 || tx >= a.length || ty >= a[0].length)
continue;
if(a[tx][ty] == '+')
continue;
if((tx == 0 || tx == a.length - 1) && ty >= 0 && ty < a[0].length && a[tx][ty] == '.') {
q = Math.min(q, tstep);
continue;
}
if((ty == 0 || ty == a[0].length - 1) && tx >= 0 && tx < a.length && a[tx][ty] == '.') {
q = Math.min(q, tstep);
continue;
}
a[tx][ty] = '+';
que.add(new Pos(tx,ty,tstep));
}
}
}
}
class Pos{
int x;
int y;
int step;
public Pos(int x,int y,int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
以上是在比赛所写,可能会有些冗余。