AcWing_4318_最短路径
2022-03-27 02:00 幻霞 阅读(37) 评论(0) 收藏 举报链接:https://www.acwing.com/problem/content/submission/code_detail/12529624/

这道题目一开始的思路想的太简单,给出了一个路径,将这个路径看做唯一能走的地图,然后判断是否有相邻或者相交,
然而事实上测试样例中含有像UDR这种东西能够把标记法直接干碎的数据 (然而事实上是笔者把某一步想的太绝对了)。
因此不能大意,干脆摆烂一下,用默认起点(101,101)读入路径后可算出终点(x,y),从终点dfs回起点,更新到达每一个位置的最小长度,然后判断终点的长度即可。
#include<bits/stdc++.h>
using namespace std;
int m[305][305]= {0};
int ssize;
void dfs(int x,int y,int len) {
static int dx[4]= {-1,1,0,0},dy[4]= {0,0,-1,1};
for(int i=0; i<4; i++) {
int tx=x+dx[i],ty=y+dy[i];
//先计算下一个路径的值
if(m[tx][ty]==-1) m[tx][ty]=len+1;
}
for(int i=0; i<4; i++) {
int tx=x+dx[i],ty=y+dy[i];
//只有比原来的值小的最优路径才会去覆盖
if(m[tx][ty]>=len+1) dfs(tx,ty,len+1);
}
}
int main() {
string s;
cin>>s;
int x=101,y=101;
m[101][101]=-1;
for(int i=0; i<s.size(); i++) {
if(s[i]=='L') x--;
else if(s[i]=='R') x++;
else if(s[i]=='U') y++;
else if(s[i]=='D') y--;
m[x][y]=-1;
}
dfs(x,y,1);
if(m[101][101]<s.size()) cout<<"NO";
else cout<<"YES";
return 0;
}
看到这想到很久以前写的一些寻路算法,改天研究一下。
浙公网安备 33010602011771号