Pagini recente » Cod sursa (job #756579) | Cod sursa (job #2007354)
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream in ("barbar.in");
ofstream out ("barbar.out");
int const nmax = 1000;
char v[1 + nmax][1 + nmax];
int dist[1 + nmax][1 + nmax];
int path[1 + nmax][1 + nmax];
int n ,m;
struct Square{
int x;
int y;
};
int const iplus[4] = {1 , -1 ,0 ,0};
int const jplus[4] = {0 ,0 ,-1 ,1};
bool valid(int x ,int y){
return (1 <= x && x <= n) && (1 <= y && y <= m);
}
void flood(){///for dragons
queue <Square> q;
for(int i = 1 ; i <= n ;i++){
for(int j = 1 ; j <= m ;j++){
if(v[i][j] == 'D'){
q.push({i , j});
dist[i][j] = 0;
}
}
}
while(0 < q.size()){
int x = q.front().x;
int y = q.front().y;
q.pop();
for(int h = 0 ; h < 4 ;h++){
int newx = x + iplus[h];
int newy = y + jplus[h];
if(valid(newx , newy) && (dist[newx][newy] == -1 || dist[x][y] + 1 < dist[newx][newy])){
dist[newx][newy] = dist[x][y] + 1;
q.push({newx , newy});
}
}
}
}
void computepath(int x , int y){
queue <Square> q;
q.push({x , y});
path[x][y] = dist[x][y];
while(0 < q.size()){
x = q.front().x;
y = q.front().y;
q.pop();
for(int h = 0 ; h < 4 ;h++){
int newx = x + iplus[h];
int newy = y + jplus[h];
if(v[newx][newy] != '*' && valid(newx , newy) && (path[newx][newy] == -1 || path[newx][newy] < min(path[x][y] , dist[newx][newy]) )){
path[newx][newy] = min(path[x][y] , dist[newx][newy]);
q.push({newx , newy});
}
}
}
}
int main()
{
in>>n>>m;
for(int i = 1 ; i <= n ;i++){
for(int j = 1 ; j <= m ;j++){
in>>v[i][j];
dist[i][j] = -1;
path[i][j] = -1;
}
}
int startx , starty;
int stopx , stopy ;
for(int i = 1 ; i <= n ;i++){
for(int j = 1 ; j <= m ;j++){
in>>v[i][j];
if(v[i][j] == 'I'){
startx = i;
starty = j;
}
if(v[i][j] == 'O'){
stopx = i;
stopy = j;
}
}
}
flood();
cout<<":";
/*
for(int i = 1 ; i <= n ;i++){
for(int j = 1 ; j <= m ;j++){
cout<<dist[i][j]<<" ";
}
cout<<'\n';
}
cout<<'\n';
*/
computepath(startx , starty);
/*
for(int i = 1 ; i <= n ;i++){
for(int j = 1 ; j <= m ;j++){
cout<<path[i][j]<<" ";
}
cout<<'\n';
}
*/
out<<path[stopx][stopy];
return 0;
}