蓝桥杯 BFS 高桥买酒

问题描述

4 5

s####

....#

#####

#...g

解题思路

tips生成x,y坐标轴的两个队列,根据队列的特性进行广度搜索

参考代码

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

public class Main {
	//访问节点的x,y坐标
	static Queue<Integer> x = new LinkedList<Integer>();
	static Queue<Integer> y = new LinkedList<Integer>();
	
	static char[][] map;//输入样例的地图
	static boolean[][] check;//同步地图的访问状态
	//坐标轴移动数组
	static int[] dx = { 1, -1, 0, 0};
	static int[] dy = { 0, 0, -1, 1};
	
public static void main(String[] args) {
	Scanner sr = new Scanner(System.in);
	int n = sr.nextInt();
	int m = sr.nextInt();
	map = new char[n][m];//原地图
	check = new boolean[n][m];//访问状态矩阵
	
	for (int i = 0; i < map.length; i++) {
		String s = sr.next();
		map[i] = s.toCharArray();
		//创建地图同时获取s的位置
		if(s.contains("s")){
			x.add(i);
			y.add(s.indexOf("s"));
			check[x.peek()][y.peek()] = true;
		}
	}
	
	if (bfs()) {
		System.out.println("YES");
	}else {
		System.out.println("NO");
	}
}
private static boolean bfs() {
	// TODO Auto-generated method stub
	//广度搜索条件:x,y队列还有元素
	while (!x.isEmpty()) {
		//取出队列中的坐标
		int tx = x.poll();
		int ty = y.poll();
		//根据移动方向,生成新的坐标
		for (int i = 0; i < dx.length; i++) {
			int nx = tx + dx[i];
			int ny = ty + dy[i];
			//不越界的情况下,判定新坐标访问的位置不是#,并且未被访问过
			if (nx >= 0 && ny >= 0 && nx < map.length && ny < map[0].length && map[nx][ny] != '#' && !check[nx][ny]) {
				//将新的陆地坐标加入队列
				x.add(nx);
				y.add(ny);
				check[nx][ny] = true;//将新的陆地坐标标记访问
				//访问到g返回YES
				if (map[nx][ny] == 'g') {
					return true;
				}
			}
		}
	}
	
	
	return false;
}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一条小传传

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值