走迷宫-蓝桥杯-bfs-Java

 

 bfs模板题,求最短路径。第一层放入起点位置,往下遍历

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;


public class Main {
	static int n,m,len,res;
	static int startx,starty,endx,endy;
	static int map[][],flag[][];
	static int dir[][] = {
			{0,1},{1,0},{-1,0},{0,-1}
	};
	static class Node{
		int x;
		int y;
		public Node(int x,int y){
			this.x =x;
			this.y =y;
		}
	}
	static Queue<Node> q = new LinkedList<>();
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		m = sc.nextInt();
		map = new int[n][m];
		flag = new int[n][m];
		for(int i =0;i<n;i++){
			for(int j=0;j<m;j++){
				map[i][j] = sc.nextInt();
			}
		}
		startx = sc.nextInt()-1;//因为数组下标从0开始
		starty = sc.nextInt()-1;
		endx = sc.nextInt()-1;
		endy = sc.nextInt()-1;
		//1为路,其他为障碍
		Node temp = new Node(startx,starty);
		q.add(temp);
		len = q.size();
		bfs();
		if (flag[endx][endy] == 0) { // 没有到达终点
            System.out.println(-1);
        } else { // 到达终点
            System.out.println(res);
        }
		
	}
	private static void bfs() {
		while(q.size()!=0){
			Node now = q.poll();
			if(now.x == endx && now.y == endy){
				
				return;
			}
			for(int i =0;i<4;i++){
				int dx = now.x + dir[i][0];
				int dy = now.y + dir[i][1];
				if(pd(dx,dy)){
					flag[dx][dy] = 1;
					Node last = new Node(dx,dy);
					q.add(last);
				}
			}
			len--;
			if(len == 0){
				res ++;
				len = q.size();
			}
		}
		
	}
	
	private static boolean pd(int dx, int dy) {
		if(dx<0 || dx>=n||dy<0||dy>=m){
			return false;
		}
		if(map[dx][dy] != 1 || flag[dx][dy] !=0){
			return false;
		}
		return true;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值