迷宫中离入口最近的出口

原题链接:迷宫中离入口最近的出口

这是一道经典的迷宫题,也是经典的最短路径。
通常我们最短路径,会使用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;
	}
}

以上是在比赛所写,可能会有些冗余。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值