Train of Thought: Simple simulation, just follow the instructions given by the path in the matrix, and output the number of steps or the number of steps in the cyclic state
[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", & 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;
}