思路:簡單的模擬,按照矩陣中路徑給出的指令走就是了,輸出走的步數或者循環狀態的步數
[cpp]
#include<stdio.h>
#include<string.h>
int map[15][15],a[15][15];
int n,m,k,kind,link;
bool flag;
void Init()
{
memset(map,0,sizeof(map));
int i;
for(i=0;i<=n+1;i++)
{
map[i][0]=-1;map[i][m+1]=-1;
}
for(i=0;i<=m+1;i++)
{
map[0][i]=-1;map[n+1][i]=-1;
}
}
void dfs(int x,int y)
{
if(map[x][y]==-1)
{
flag=true;
return;
}
map[x][y]=++kind;
if(a[x][y]==1)
{
if(map[x][y+1]>0)
{
link=map[x][y]-map[x][y+1]+1;
kind=map[x][y+1]-1;
return;
}
else
dfs(x,y+1);
}
if(a[x][y]==2)
{
if(map[x][y-1]>0)
{
link=map[x][y]-map[x][y-1]+1;
kind=map[x][y-1]-1;
return;
}
else
dfs(x,y-1);
}
if(a[x][y]==3)
{
if(map[x+1][y]>0)
{
link=map[x][y]-map[x+1][y]+1;
kind=map[x+1][y]-1;
return;
}
else
dfs(x+1,y);
}
if(a[x][y]==4)
{
if(map[x-1][y]>0)
{
link=map[x][y]-map[x-1][y]+1;
kind=map[x-1][y]-1;
return;
}
else
dfs(x-1,y);
}
}
int main()
{
int i,j;
char ch[15];
while(scanf("%d%d",&n,&m)!=EOF&&(n+m))
{
scanf("%d",&k);
Init();
for(i=1;i<=n;i++)
{
scanf("%s",ch);
for(j=0;j<m;j++)
{
if(ch[j]=='E')
a[i][j+1]=1;
if(ch[j]=='W')
a[i][j+1]=2;
if(ch[j]=='S')
a[i][j+1]=3;
if(ch[j]=='N')
a[i][j+1]=4;
}
}
kind=0;flag=false;
dfs(1,k);
if(flag) printf("%d step(s) to exit\n",kind);
else printf("%d step(s) before a loop of %d step(s)\n",kind,link);
}
return 0;
}