G 清楚姐姐逛街(Easy Version)【2023牛客寒假算法基础集训营4】
G 清楚姐姐逛街(Easy Version)
题意
终点会按照固定方式移动的搜索问题,多次查询
思路
- 只要时间t是确定的,那么终点的位置就是确定的 -> 可以模拟每一时刻
- bfs维护智乃到每个点的最短距离
- 模拟每一时刻清楚姐姐的位置
- 如果该时刻大于智乃到每个点的最短距离(前提是智乃能够到达该位置)则为答案
代码
点击查看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
#define X first
#define Y second
typedef long long LL;
typedef pair<int,int> pii;
const char nl = '\n';
const int N = 810;
const int M = 810;
int n,m,x,y,q;
int z[N][M],qc[N][M],dx[]={-1,1,0,0},dy[]={0,0,1,-1};
char g[N][M];
void bfs(){
queue<pair<pii,int>> q;
q.push({{x,y},0}); //储存坐标和最短距离
z[x][y] = 0; //记得要初始化原点为0
while(q.size()){
auto u = q.front();
q.pop();
for(int i = 0; i < 4; i ++){
int nx = u.X.X + dx[i];
int ny = u.X.Y + dy[i];
if(nx < 0 || nx >= n || ny < 0 || ny >= m || g[nx][ny] == '#' || z[nx][ny] != -1)continue;//出界或者不能走或者已经走过
else{
q.push({{nx,ny},u.Y+1});
z[nx][ny] = u.Y + 1; //下一个点最短距离等于当前点最短距离+1
}
}
}
}
void solve(){
cin >> n >> m >> x >> y >> q;
for(int i = 0;i < n; i ++){
for(int j = 0; j < m; j ++){
cin >> g[i][j];
}
}
memset(z,-1,sizeof z); //初始化为-1
bfs(); //维护智乃到某一的最短距离
while(q--){
bool f = 0;
int a,b;
cin >> a >> b;
int na = a,nb = b;
int t = 0;
while(t<n*m){//清楚姐姐走完全地图最多有n*m
t ++; //模拟每一时刻的动作
char c = g[na][nb];
if(c == 'L'&&g[na][nb-1]!='#')nb -= 1;//如果能走
else if(c == 'R'&&g[na][nb+1]!='#')nb += 1;
else if(c == 'U'&&g[na-1][nb]!='#')na -= 1;
else if(c == 'D'&&g[na+1][nb]!='#')na += 1;
if(t >= z[na][nb] && z[na][nb] != -1){
cout << t << nl;
f = 1;
break;
}
}
if(!f)cout << -1 << nl;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
solve();
}
标签:
2023牛客寒假算法基础集训营
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】