时间:1s 空间:256M
题目描述:
有一个 n×m 的地图,空地为’.’,高楼为’#‘,小信的家在 ‘S’。 小信想找一条锻炼身体的路径,路径需要从家出发,不经过相同的空地,最后回到家。出于锻炼身体的目的,这条路径的长度必须至少为4,也就是说除了终点和起点都是家以外,经过的不同的空地个数至少为 3。 小信想知道这样的路径存不存在。当然,小信无法通过有高楼的地方,所以可能不存在这样的路径。
输入格式:
第一行包含两个整数 n,m。 接下来包含一个 n×m 的地图,地图只包含 ’.’,’#’,‘S’ 三种字符。
输出格式:
如果存在锻炼身体的路径,输出”Yes”,否则输出”No”。
样例1输入:
4 4 … #.#. #S#. …
样例1输出:
Yes
样例2输入:
4 4 .#.. #.#. #S#. …
样例2输出:
No
约定:
对于100%的数据,2≤n,m≤,4≤n⋅m≤。
思路:
这是一个特殊的dfs,因为他的头和尾是同一个地方,还有一个很miao的地方,就是运动数组
int tx[4]= {1,0,-1,0};
int ty[4]= {0,-1,0,1};这么写他会挂。
标程:
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int INF=0x3f3f3f3f;
int tx[4]= {1,-1,0,0};
int ty[4]= {0,0,-1,1};
int n,m;
map<pair<int,int>,bool> mp;
map<pair<int,int>,int> flag;
void dfs(int x,int y,int x_end,int y_end,int step=0) {
if(x==x_end&&y==y_end&&step) {
if(step>=4) {
cout<<"Yes";
exit(1);
} else {
return;
}
}
if(step&&step<=flag[ {x,y}]) {
return;
}
else {
flag[ {x,y}]=step;
}
for(int i=0; i<4; i++) {
int fx=x+tx[i];
int fy=y+ty[i];
if(fx>=1&&fx<=n&&fy>=1&&fy<=m&&mp[ {fx,fy}]) {
mp[ {fx,fy}]=0;
dfs(fx,fy,x_end,y_end,step+1);
mp[ {fx,fy}]=1;
}
}
return;
}
int main() {
int str_i,str_j;
cin>>n>>m;
for(int i=1; i<=n; i++) {
for(int j=1; j<=m; j++) {
char ch;
cin>>ch;
if(ch=='S') {
str_i=i;
str_j=j;
mp[{i,j}]=1;
} else if(ch=='#') {
mp[{i,j}]=0;
} else {
mp[{i,j}]=1;
}
}
}
dfs(str_i,str_j,str_i,str_j);
cout<<"No";
return 0;
}