Pagini recente » Cod sursa (job #1401628) | Cod sursa (job #2194898) | Cod sursa (job #1899155) | Cod sursa (job #1018709) | Cod sursa (job #1238401)
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int nmax=1005;
char a[nmax][nmax];
int d[nmax][nmax];
bool viz[nmax][nmax];
int vmax;
int r, c;
pair <int, int> start;
pair <int, int> finish;
queue < pair<int, int> > drag;
int x[]={-1, 0, 1, 0}, y[]={0, 1, 0, -1};
inline bool verif(int i, int j)
{
return i>=0 && j>=0 && i<r && j<c;
}
void bfs()
{
while(!drag.empty())
{
pair <int, int> temp=drag.front();
for(int i=0;i<4;i++)
{
pair <int, int> current(temp.first+x[i], temp.second+y[i]);
int u=temp.first+x[i];
int v=temp.second+y[i];
if(verif(u, v) && a[u][v]!='*' && d[u][v]==0)
{
drag.push(current);
d[u][v]=d[temp.first][temp.second]+1;
vmax=max(vmax, d[u][v]);
}
}
drag.pop();
}
}
void bfss()
{
queue <pair <int, int> > t;
queue <pair <int, int> > q;
t.push(start);
while(!t.empty() && vmax>=0)
{
while(!t.empty())
{
q.push(t.front());
t.pop();
}
while(!q.empty())
{
pair <int, int> temp=q.front();
bool ok;
for(int i=0;i<4;i++)
{
ok=true;
pair <int, int> current(temp.first+x[i], temp.second+y[i]);
int u=temp.first+x[i];
int v=temp.second+y[i];
if(verif(u, v) && a[u][v]!='*' && (!viz[u][v]) && d[u][v]>=vmax)
{
viz[u][v]=1;
ok=false;
q.push(current);
}
}
q.pop();
if(ok) t.push(temp);
}
if(viz[finish.first][finish.second]==1)return ;
if(!t.empty()) vmax--;
}
}
int main()
{
freopen("barbar.in", "r", stdin);
freopen("barbar.out", "w", stdout);
scanf("%d%d", &r, &c);
scanf("\n");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
scanf("%c", &a[i][j]);
if(a[i][j]=='D')
drag.push(pair <int, int> (i, j));
if(a[i][j]=='I')
start=pair <int, int> (i, j);
if(a[i][j]=='O')
finish=pair <int, int> (i, j);
}
scanf("\n");
}
bfs();
bfss();
printf("%d\n", min(vmax, d[start.first][start.second]));
return 0;
}