题目链接。
分析:
很简单的一道题,
#include <iostream> #include <cstring> #include <cstdio> #include <cstdlib> #include <stack> #include <cmath> #include <queue> using namespace std; const int maxn = 100; int dx[] = {-1, 0, 1, 0};//上右下左 int dy[] = {0, 1, 0, -1}; char G[maxn][maxn]; int step[maxn][maxn]; bool vis[maxn][maxn]; int n, m, ex_step, lo_step; bool solve(int s) { memset(vis, false, sizeof(vis)); step[0][s-1] = 1; vis[0][s-1] = true; int x = 0, y = s-1, nx, ny; while(true) { switch(G[x][y]) { case 'N': nx = x + dx[0]; ny = y + dy[0]; break; case 'E': nx = x + dx[1]; ny = y + dy[1]; break; case 'S': nx = x + dx[2]; ny = y + dy[2]; break; case 'W': nx = x + dx[3]; ny = y + dy[3]; break; } if(nx < 0 || nx >= n || ny < 0 || ny >= m) { ex_step = step[x][y]; return true; } if(!vis[nx][ny]) { //exit vis[nx][ny] = true; step[nx][ny] = step[x][y] + 1; x = nx; y = ny; } else {//发现环 lo_step = step[x][y] + 1 - step[nx][ny]; ex_step = step[nx][ny] - 1; return false; } } } int main() { int s; while(scanf("%d%d%d", &n, &m, &s) == 3) { if(n == 0 && m == 0 && s == 0) break; for(int i=0; i<n; i++) scanf("%s", G[i]); if(solve(s)) printf("%d step(s) to exit ", ex_step); else printf("%d step(s) before a loop of %d step(s) ", ex_step, lo_step); } return 0; }