This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//#pragma gcc optimize("O2")
#include <bits/stdc++.h>
//#include<complex>
using namespace std;
#define int long long
int n;int m;
string gr[510];
int dir[5]={0,1,0,-1,0};
int odis[510][510];
int dis[510][510];
int bsd(int x,int y){
for(int d=1;d<=4;d++){
int a=x+dir[d-1];int b=y+dir[d];
if(gr[a][b]=='#'){return 1;}
}
return 0;
}
void fbfs(){
queue<pair<int,int>>q;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
odis[i][j]=1e9;
if(gr[i][j]!='#'&&bsd(i,j)){
q.push({i,j});
odis[i][j]=0;
}
}
}
while(q.size()){
int nwx=q.front().first;
int nwy=q.front().second;
q.pop();
for(int i=1;i<=4;i++){
int x=nwx+dir[i-1];int y=nwy+dir[i];
if(gr[x][y]=='#'){continue;}
if(odis[x][y]>odis[nwx][nwy]+1){
odis[x][y]=odis[nwx][nwy]+1;
q.push({x,y});
}
}
}
}
int vis[510][510];
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>gr[i];
gr[i]="#"+gr[i]+"#";
}
pair<int,int>st;
pair<int,int>en;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
odis[i][j]=1e9;
dis[i][j]=1e9;
if(gr[i][j]=='C'){
st={i,j};
// pq.push_back({{i,j},0});
}
if(gr[i][j]=='F'){
en={i,j};
}
}
}
fbfs();
priority_queue<pair<int,pair<int,int>>,vector<pair<int,pair<int,int>>>,greater<pair<int,pair<int,int>>>>pq;
pq.push({0,st});
dis[st.first][st.second]=0;
while(pq.size()){
int nwx=pq.top().second.first;
int nwy=pq.top().second.second;
pq.pop();
if(vis[nwx][nwy]){continue;}
vis[nwx][nwy]=1;
for(int i=1;i<=4;i++){
int x=nwx+dir[i-1];
int y=nwy+dir[i];
if(gr[x][y]=='#'){continue;}
if(dis[x][y]>dis[nwx][nwy]+1){
dis[x][y]=dis[nwx][nwy]+1;
pq.push({dis[x][y],{x,y}});
}
while(gr[x+dir[i-1]][y+dir[i]]!='#'){
x+=dir[i-1];y+=dir[i];
}
if(dis[x][y]>dis[nwx][nwy]+1+odis[nwx][nwy]){
dis[x][y]=dis[nwx][nwy]+1+odis[nwx][nwy];
pq.push({dis[x][y],{x,y}});
}
}
}
if(dis[en.first][en.second]>n*m){
cout<<"nemoguce";return 0;
}
cout<<dis[en.first][en.second]<<"\n";
}
# | 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... |
# | 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... |