A robot has been programmed to follow the instructions in its path. Instructions for the next direction the robot is to move are laid down in a grid. The possible instructions are
N north (up the page)
S south (down the page)
E east (to the right on the page)
W west (to the left on the page)
For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid.
Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits.
You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around.
关于这个题,主要运用dfs模拟这个过程。在写这道题时遇到很多错误,主要就是根据题意模拟这个过程。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; char s[1005][1005]; int vis[1005][1005],m,n,k,flag; void dfs(int a,int b){ int step=1; // step记录走的步数 while(1){ // 模拟这个过程 if(a == m || a < 0 || b < 0 || b == n){ // 超过这个矩阵时退出 printf("%d step(s) to exit\n",step-1); return; } if(vis[a][b]){ // 标记,如果这个点走过时,就会退出 printf("%d step(s) before a loop of %d step(s)\n",vis[a][b]-1,step-vis[a][b]); return; } vis[a][b] = step; if(s[a][b] == 'N') a--; else if(s[a][b] == 'S') a++; else if(s[a][b] == 'E') b++; else if(s[a][b] == 'W') b--; step++; } } int main(){ while(cin >> m>>n>>k&&n&&m){ memset(vis,0,sizeof(vis)); for(int i = 0;i < m ;i++) scanf("%s",s[i]); k--; // 因为是从0,开始的,所以就减去1 dfs(0,k); } return 0; }