官方题解
2025-12-01 00:12:33
发布于:浙江
34阅读
0回复
0点赞
题目大意
判断通过题目给出的行走路线,是否会经过重复的位置。
解题思路
考虑记录所有走过的位置,如果某个位置经历过两次及以上,则输出 Yes 。
但显然无法用二维数组直接记录,那么考虑使用 map<pair<int,int>,bool> ,其中 pair<int,int> 用于存放二维坐标 。当移动到坐标 发现 map 中已经记录过此位置,则输出 Yes 。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int main(){
int n;cin>>n;
string s;cin>>s;
int x=0,y=0;
map<pair<int,int>,bool>mp;
mp[{0,0}]=true;
for(auto ch:s){
if(ch=='R') y++;
if(ch=='L') y--;
if(ch=='U') x--;
if(ch=='D') x++;
if(mp.count({x,y})){
cout<<"Yes"<<endl;
return 0;
}
mp[{x,y}]=true;
}
cout<<"No"<<endl;
return 0;
}
这里空空如也






有帮助,赞一个