AcWing 1112. 迷宫 题解(搜索)

这篇博客介绍了如何使用BFS(广度优先搜索)算法解决AcWing1112题目的迷宫问题。作者首先展示了如何初始化状态并设置边界条件,然后通过读取迷宫地图和起点终点坐标。接着,利用BFS进行搜索,如果找到目标点则返回true,否则返回false。代码中包括了队列操作和邻接节点的遍历。
摘要由CSDN通过智能技术生成

AcWing 1112. 迷宫
虽然是DFS题,但是BFS也能写,看了一下y总的代码,思路差不多,就记录自己写的BFS版本了

#include<bits/stdc++.h>

using namespace std;

const int N = 105;
#define x first
#define y second
typedef pair<int, int>PII;

int n, k;
char g[N][N];
int ha, la, hb, lb;
bool st[N][N];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
queue<PII>q;

bool dfs(){
	//初始化 
	memset(st, 0, sizeof st);
    while(q.size()) q.pop(); 
    memset(g, 0, sizeof g);
    
	cin>>n;
    for(int i = 0; i < n; i ++ ){
        for(int j = 0; j < n; j ++ ){
            cin>>g[i][j];
        }
    }
    cin>>ha>>la>>hb>>lb;
    if(g[ha][la] == '#' || g[hb][lb] == '#') return false;
    if(ha == hb && la == lb) return true;
    q.push({ha, la});
    st[ha][la] = true;
	
	while(q.size()){
		int xx = q.front().x;
		int yy = q.front().y;
	//	cout<<xx<<' '<<yy<<endl;
		q.pop();
		for(int i = 0; i < 4; i ++ ){
			int xxx = xx + dx[i];
			int yyy = yy + dy[i];
			if(xxx < 0 || yyy < 0) continue;
			if(xxx < n && yyy < n && xxx >= 0 && yyy >= 0 && !st[xxx][yyy] && g[xxx][yyy] != '#'){
				if(xxx == hb && yyy == lb) return true;
				q.push({xxx, yyy});
				st[xxx][yyy] = true;
			} 
		}
	} 
    return false;
}

int main()
{
    cin>>k;
    while(k -- ){
        if(dfs()) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值