又是一个机器人,按照棋盘相应位置指示走。要么走出棋盘,要么死循环。较简单。
#include <iostream>
#include <stdio.h>
#include <string.h>
//#define TEST
using namespace std;
char s[20];
char M[20][20];
int path[20][20];
int main()
{
#ifdef TEST
freopen("test.txt", "r", stdin);
#endif // TEST
int r, c, start;
while(1)
{
scanf("%d %d %d", &r, &c, &start);
if(r == 0 && c == 0 && start == 0) break;
memset(M, '\0', sizeof(M));
memset(path, 0, sizeof(path));
for(int i = 0; i < r; i++)
{
scanf("%s", s);
for(int j = 0; j < strlen(s); j++)
M[i][j] = s[j];
}
int cx = 0, cy = start-1;
int cnt = 1;
path[cx][cy] = cnt;
while(1)
{
int nx, ny;
switch(M[cx][cy])
{
case 'E': nx = cx; ny = cy+1;break;
case 'S': nx = cx + 1; ny = cy; break;
case 'W': nx = cx; ny = cy - 1; break;
case 'N': nx = cx - 1; ny = cy;break;
default:nx = cx; ny = cy;
}
// yue bian jie
if(nx < 0 || nx == r || ny < 0 || ny == c)
{
printf("%d step(s) to exit\n", cnt);
break;
}
else if(path[nx][ny] != 0)
{
printf("%d step(s) before a loop of %d step(s)\n", path[nx][ny]-1, path[cx][cy]-path[nx][ny]+1);
break;
}
else
{
path[nx][ny] = ++cnt;
cx = nx;
cy = ny;
}
}
}
return 0;
}