Pagini recente » Cod sursa (job #2262184) | Cod sursa (job #240845) | Cod sursa (job #906252) | Cod sursa (job #1283763) | Cod sursa (job #1736776)
#include <fstream>
#include <cstdio>
#include <math.h>
#include <algorithm>
#include <queue>
using namespace std;
#define llu long long unsigned
#define ll long long
#define pb push_back
#define mp make_pair
string problemName = "barbar";
string inFile = problemName+".in";
string outFile = problemName+".out";
ifstream fin(inFile.c_str());
ofstream fout(outFile.c_str());
const int N = 1005;
char h[N][N];
int danger[N][N], dp[N][N];
queue < pair<int, int> > q;
int d[4][2] = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1}
};
void go(int xS, int yS){
int x, y, nx, ny, i;
q.push({xS, yS});
while(q.empty() == false){
x = q.front().first;
y = q.front().second;
q.pop();
for(i = 0;i < 4;i++){
nx = x + d[i][0];
ny = y + d[i][1];
if(dp[nx][ny] == 1e9 && h[nx][ny] != '*'){
dp[nx][ny] = min(dp[x][y], danger[nx][ny]);
q.push({nx, ny});
}else if(min(dp[x][y], danger[nx][ny]) > dp[nx][ny] && h[nx][ny] != '*'){
dp[nx][ny] = min(dp[x][y], danger[nx][ny]);
q.push({nx, ny});
}
}
}
}
int main(){
int n, m, i, j, x, y, nx, ny, xS, yS, xF, yF;
fin>>n>>m;
for(i = 1;i <= n;i++){
fin>>h[i]+1;
}
for(i = 0;i <= n+1;i++){
h[i][0] = h[i][m+1] = '*';
}
for(i = 0;i <= m+1;i++){
h[0][i] = h[n+1][i] = '*';
}
for(i = 1;i <= n;i++){
for(j = 1;j <= m;j++){
danger[i][j] = -1;
dp[i][j] = 1e9;
if(h[i][j] == 'D'){
q.push({i, j});
danger[i][j] = 0;
}else if(h[i][j] == 'I'){
xS = i;
yS = j;
}else if(h[i][j] == 'O'){
xF = i;
yF = j;
}
}
}
while(q.empty() == false){
x = q.front().first;
y = q.front().second;
q.pop();
for(i = 0;i < 4;i++){
nx = x + d[i][0];
ny = y + d[i][1];
if(danger[nx][ny] == -1 && h[nx][ny] != '*'){
danger[nx][ny] = danger[x][y] + 1;
q.push({nx, ny});
}
}
}
// for(i = 1;i <= n;i++){
// for(j = 1;j <= m;j++){
// fout<<danger[i][j]<<' ';
// }
// fout<<'\n';
// }
dp[xS][yS] = danger[xS][yS];
go(xS, yS);
// fout<<"\n\n";
// for(i = 1;i <= n;i++){
// for(j = 1;j <= m;j++){
// if(dp[i][j] == 1e9){
// fout<<-1<<' ';
// }else{
// fout<<dp[i][j]<<' ';
// }
// }
// fout<<'\n';
// }
if(dp[xF][yF] != 1e9){
fout<<dp[xF][yF];
}else{
fout<<-1;
}
return 0;
}