题意:一个地图标有wsen四个方向,走到每个点就按照节点的方向走一步,问在多少步后进入循环或者走出地图
题解:BFS 每个点打一个时间戳,重复或出地图就退出
#include<bits/stdc++.h>
using namespace std;
int n,m,st;
void Gao()
{
int f[300][300];
char s[300][300];
memset(f,-1,sizeof(f));
for (int i=1;i<=n;i++)
scanf("%s",s[i]);
int x=1,y=st;
int t=0;
while (true)
{
if (x<1||x>n||y<1||y>m)
{
printf("%d step(s) to exit\n",t);
return;
}
if (f[x][y]!=-1)
{
printf("%d step(s) before a loop of %d step(s)\n",f[x][y],t-f[x][y]);
return ;
}
f[x][y]=t++;
if (s[x][y-1]=='N')
{
x--;
continue;
}
if (s[x][y-1]=='S')
{
x++;
continue;
}
if (s[x][y-1]=='W')
{
y--;
continue;
}
if (s[x][y-1]=='E')
{
y++;
continue;
}
}
}
int main()
{
while (cin>>n>>m>>st&&n&&m&&st)
Gao();
return 0;
}