#include<fstream>
#include<iostream>
using namespace std;
#define maxn 102
#define limit 10000
char matrix[maxn][maxn];
char path[maxn*maxn];
//[i,j+1] [i-1,j] [i,j-1] [i+1,j]
//0 's', 1 'e', 2'n', 3'w'
int left_pos[4][2] = {{0,1},{-1,0},{0,-1},{1,0}};
int next_pos[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
char direction[4] = {'S','E','N','W'};
int turnLeft(int cur)
{
return (cur+1+4)%4;
}
int turnRight(int cur)
{
return (cur-1+4)%4;
}
int func(int sx,int sy,int ex,int ey)
{
int ret = 0;
int old_ret = ret;
int i = sx;
int j = sy;
int cur_dir = -1;
int complete = 0;
int k = 0;
int start_dir;
while(k <4 )
{
if(matrix[i+left_pos[k][0]][j+left_pos[k][1]] == '#'
&& matrix[i+next_pos[k][0]][j+next_pos[k][1]] == '.')
{
cur_dir = k;
break;
}
k++;
}
if(cur_dir < 0) return -1;
start_dir = cur_dir;
while(ret < limit)
{
if(matrix[i+next_pos[cur_dir][0]][j+next_pos[cur_dir][1]] == '.'){
i += next_pos[cur_dir][0];
j += next_pos[cur_dir][1];
path[ret++] = direction[cur_dir];
if(i == ex && j == ey) return ret;
k = 0;
}
if(k >= 3) break;
if(ret > 0 && i == sx && j== sy ) break;
if(matrix[i+left_pos[cur_dir][0]][j+left_pos[cur_dir][1]] == '.')
cur_dir = turnLeft(cur_dir);
else if(matrix[i+next_pos[cur_dir][0]][j+next_pos[cur_dir][1]] == '#')
cur_dir = turnRight(cur_dir);
k++;
}
return -1;
}
int main()
{
int T,N,sx,sy,ex,ey;
ifstream in("D-large-practice.in");
ofstream out("d.out");
in>>T;
for(int i = 0;i<T;i++)
{
in >> N;
for(int j = 1;j<=N;j++)
{
for(int k = 1;k<=N;k++)
{
in>>matrix[j][k];
}
}
for(int j = 0;j<=N+1;j++)
{
matrix[0][j] = '#';
matrix[N+1][j] = '#';
matrix[j][0] = '#';
matrix[j][N+1] = '#';
}
in>>sx>>sy>>ex>>ey;
int ret = func(sx,sy,ex,ey);
out<<"Case #"<<i+1<<": ";
if(ret < 0){
out<<"Edison ran out of energy."<<endl;
}else{
out<<ret<<endl;
for(int k = 0;k< ret;k++)
out<<path[k];
out<<endl;
}
}
in.close();
out.close();
return 0;
}
GoogleJam_Cross the maze
最新推荐文章于 2017-04-09 14:18:23 发布