思路:构造模型
#include<iostream>
using namespace std;
int N[2] = {-1,0};
int S[2] = {1,0};
int E[2] = {0,1};
int W[2] = {0,-1};
char map[12][12] = {'Q'};
int flag[12][12]={0};
int main()
{
int row, col, start;
char s[10];
int i, j;
while ((cin >> row >> col >> start) && ((row != 0) || (col != 0) || (start != 0)))
{
//clear map and flag
for (i = 0; i < 12; i++)
{
for (j = 0; j < 12; j++)
{
map[i][j] = 'Q';
flag[i][j]=0;
}
}
//set map data
for (i = 0; i < row; i++)
{
cin >> s;
for (j = 0; j < col; j++)
{
map[i + 1][j + 1] = s[j];
}
}
//function start_location=[1][start]
int over=0;
int loc_x=1;
int loc_y=start;
int step=0;
int loop=0;
flag[loc_x][loc_y]=1;
while (1)
{
switch(map[loc_x][loc_y])
{
case 'N':
loc_x=loc_x+N[0];
loc_y=loc_y+N[1];
break;
case 'S':
loc_x=loc_x+S[0];
loc_y=loc_y+S[1];
break;
case 'E':
loc_x=loc_x+E[0];
loc_y=loc_y+E[1];
break;
case 'W':
loc_x=loc_x+W[0];
loc_y=loc_y+W[1];
break;
}
if(flag[loc_x][loc_y]==2)
{
over=2;
break;
}
if(flag[loc_x][loc_y]==1)
{
flag[loc_x][loc_y]=2;
loop++;
}
if(flag[loc_x][loc_y]==0)
{
flag[loc_x][loc_y]=1;
step++;
}
if(map[loc_x][loc_y]=='Q')
{
over=1;
break;
}
}//end while
if(over==1)
{
cout<<step<<" step(s) to exit"<<endl;
}
else
{
cout<<step-loop+1<<" step(s) before a loop of "<<loop<<" step(s)"<<endl;
}
}
//system("pause");
return 0;
}
1154

被折叠的 条评论
为什么被折叠?



