这道题的处理方法是把待处理的字符数组边界设为空格作为出口的标志,另设一个记录所走步数的数组steps,但是这个题目分两个走法,其一没有重复的路径,遇到空格后直接输出的步数,用mark = 0标记; 另一种情况就是出现了重复的路径也就是题目中if ( steps[curi][curj] != 0 )即下一步是已经走了的路径,那么这必然是循环的开始,根据记录的step和下一个step值之间的关系就可以输出
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main ()
{
char map[13][13];
int steps[13][13];
int num, col, start;
while ( scanf ("%d %d %d", &num, &col, &start ) != EOF && ( num != 0 && col != 0 && start != 0 ) )
{
getchar ();
memset (map, 0, sizeof(map) );
memset (steps, 0, sizeof(steps) );
for ( int i = 0; i < col + 2; i ++ )
{
map[0][i] = ' ';
map[num + 1][i] = ' ';
}
for ( int i = 0; i < num + 2; i ++ )
{
map[i][0] = ' ';
map[i][col + 1] = ' ';
}
for ( int i = 1; i <= num; i ++)
{
for ( int j = 1; j <= col; j ++ )
{
scanf ("%c", &map[i][j]);
}
getchar ();
}
int step = 1;
int curi = 1; int curj = start;
int mark = 0;
int temp = 1; int t = 0;
while ( map[curi][curj] != ' ' )
{
if ( steps[curi][curj] != 0 )
{
temp = step;
t = steps[curi][curj];
mark = 1;
break;
}
else
{
steps[curi][curj] = step;
if ( map[curi][curj] == 'N' )
{
curi = curi - 1;
curj = curj;
}
else if ( map[curi][curj] == 'S' )
{
curi = curi + 1;
curj = curj;
}
else if ( map[curi][curj] == 'W' )
{
curi = curi;
curj = curj - 1;
}
else if ( map[curi][curj] == 'E' )
{
curi = curi;
curj = curj + 1;
}
step ++;
}
}
if ( mark == 0 )
printf ("%d step(s) to exit\n", step - 1 );
else
printf ("%d step(s) before a loop of %d step(s)\n", t - 1, temp - t );
}
//system ("pause");
return 0;
}
posted on 2010-08-30 15:28
雪黛依梦 阅读(346)
评论(0) 编辑 收藏 引用 所属分类:
模拟题