This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <stdio.h>
#include <queue>
#define INF 0x7fffffff
using namespace std;
queue <int> q;
int R, C, Sy, Sx, Cy, Cx, A[1001][1001], D[1001][1001], Dy[4]={0,1,0,-1}, Dx[4]={1,0,-1,0};
int Up[1001][1001], Down[1001][1001], Left[1001][1001], Right[1001][1001];
void input(void)
{
int i, j, x;
char temp[1002];
scanf("%d %d",&R,&C);
for(i=1 ; i<=R ; i++)
{
scanf("%s",&temp[1]);
for(j=1 ; j<=C ; j++)
{
if(temp[j]=='S')
{
Sy=i;
Sx=j;
}
else if(temp[j]=='C')
{
Cy=i;
Cx=j;
}
else if(temp[j]=='#')
A[i][j]=1;
D[i][j]=INF;
}
}
for(i=1 ; i<=R ; i++)
{
x=1;
for(j=1 ; j<=C ; j++)
{
if(A[i][j])
x=j+1;
else
Left[i][j]=x;
}
x=C;
for(j=C ; j>=1 ; j--)
{
if(A[i][j])
x=j-1;
else
Right[i][j]=x;
}
}
for(i=1 ; i<=C ; i++)
{
x=1;
for(j=1 ; j<=R ; j++)
{
if(A[j][i])
x=j+1;
else
Up[j][i]=x;
}
x=R;
for(j=R ; j>=1 ; j--)
{
if(A[j][i])
x=j-1;
else
Down[j][i]=x;
}
}
}
void process(void)
{
int i, y, x, ty, tx, ok;
D[Sy][Sx]=0;
q.push(Sy);
q.push(Sx);
while(!q.empty())
{
y=q.front();
q.pop();
x=q.front();
q.pop();
ok=0;
for(i=0 ; i<4 ; i++)
{
ty=y+Dy[i];
tx=x+Dx[i];
if(ty>=1 && ty<=R && tx>=1 && tx<=C && A[ty][tx]==0)
{
if(D[ty][tx]>D[y][x]+1)
{
D[ty][tx]=D[y][x]+1;
q.push(ty);
q.push(tx);
}
}
else
ok=1;
}
if(ok)
{
if(D[Up[y][x]][x]>D[y][x]+1)
{
D[Up[y][x]][x]=D[y][x]+1;
q.push(Up[y][x]);
q.push(x);
}
if(D[Down[y][x]][x]>D[y][x]+1)
{
D[Down[y][x]][x]=D[y][x]+1;
q.push(Down[y][x]);
q.push(x);
}
if(D[y][Left[y][x]]>D[y][x]+1)
{
D[y][Left[y][x]]=D[y][x]+1;
q.push(y);
q.push(Left[y][x]);
}
if(D[y][Right[y][x]]>D[y][x]+1)
{
D[y][Right[y][x]]=D[y][x]+1;
q.push(y);
q.push(Right[y][x]);
}
}
}
}
void output(void)
{
printf("%d",D[Cy][Cx]);
}
int main(void)
{
input();
process();
output();
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |