题意:给定一个n*m的矩阵指令,每个位置为‘W’,‘S’,‘N’,‘E’四个指令之一,表示四个方向。给定一个入口位置,按照所在点的指令移动。当移动出矩形区域或者出现循环的时候输出按要求进行相应输出。
思路:用一个栈记录到达过的位置。判断循环是否出现也就是当前位置是否在栈中出现。
#include <stdio.h>
#include <string.h>
char s[15][15];
struct point{
int x,y;
}stack[105];
int n,m,b,top;
int outbound(int x,int y){//(x,y)是否已经到了矩形区域外
if(x<0||y<0||x>=n||y>=m)
return 1;
return 0;
}
int hasrepead(int x,int y){//(x,y)是否在栈中出现过,返回i+1是为了当i为0的时候也能够表示出现循环
int i;
for(i = 0;i<=top;i++)
if(stack[i].x == x&& stack[i].y == y)
return i+1;
return 0;
}
int main(){
freopen("a.txt","r",stdin);
while(scanf("%d %d %d",&n,&m,&b) &&(n+m+b)){
int i,x,y;
top = -1;
for(i = 0;i<n;i++)
scanf("%s",s[i]);
stack[++top].x = x = 0;
stack[top].y = y = b-1;
while(1){
switch(s[x][y]){
case 'N':
x--;
break;
case 'W':
y--;
break;
case 'S':
x++;
break;
case 'E':
y++;
break;
}
if(outbound(x,y)){
printf("%d step(s) to exit\n",top+1);
break;
}
if(i = hasrepead(x,y)){
printf("%d step(s) before a loop of %d step(s)\n",i-1,top-i+2);
break;
}
stack[++top].x = x;
stack[top].y = y;
}
}
return 0;
}