Pagini recente » Cod sursa (job #2170407) | Cod sursa (job #1903625) | Cod sursa (job #188073) | Cod sursa (job #630455) | Cod sursa (job #2420386)
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int NMAX = 1005;
int a[NMAX][NMAX];
int dp[NMAX][NMAX];
bool viz[NMAX][NMAX];
int dx[] = {1,0,-1,0};
int dy[] = {0,1,0,-1};
int m , n;
int x1,x2,y1,y2;
struct cell{
int x,y;
};
queue<cell>q;
queue<cell>q1;
inline void qClear(){while(!q.empty()) q.pop();}
inline void init(){memset(viz,0,sizeof(viz));qClear();}
inline bool inMatrix(int x,int y){return(x<=m&&x>=1&&y>=1&&y<=n);}
inline bool verif(int med)
{
init();
cell temp,temp1;
temp.x = x1;
temp.y = y1;
q.push(temp);
while(!q.empty())
{
temp = q.front();
q.pop();
for(int i = 0 ; i < 4 ; i++)
{
temp1.x = temp.x + dx[i];
temp1.y = temp.y + dy[i];
if(!inMatrix(temp1.x,temp1.y)) continue;
if(a[temp1.x][temp1.y] == -2 || a[temp1.x][temp1.y] == -1 || viz[temp1.x][temp1.y] || dp[temp1.x][temp1.y] < med) continue;
if(temp1.x == x2 && temp1.y == y2)
return true;
viz[temp1.x][temp1.y] = 1;
q.push(temp1);
}
}
return (viz[x2][y2]);
}
int main()
{
freopen("barbar.in","r",stdin);
freopen("barbar.out","w",stdout);
char ch;
scanf("%d%d\n",&m,&n);
for(int i = 1 ; i <= m ; i++)
{
for(int j = 1 ; j < n ; j++)
{
scanf("%c",&ch);
if(ch == 'I')
{
x1 = i;
y1 = j;
continue;
}
if(ch == 'O')
{
x2 = i;
y2 = j;
continue;
}
if(ch == '*')
{
a[i][j] = -1;
continue;
}
if(ch == 'D')
{
a[i][j] = -2;
cell temp;
temp.x = i;
temp.y = j;
q1.push(temp);
continue;
}
}
scanf("%c\n",&ch);
}
cell temp;
while(!q1.empty())
{
temp = q1.front();
q1.pop();
for(int i = 0 ; i < 4 ; i++)
{
cell temp1;
temp1.x = temp.x + dx[i];
temp1.y = temp.y + dy[i];
if(!inMatrix(temp1.x,temp1.y)) continue;
if(a[temp1.x][temp1.y] == -2 || a[temp1.x][temp1.y] == -1 || dp[temp1.x][temp1.y] != 0) continue;
dp[temp1.x][temp1.y] = dp[temp.x][temp.y] + 1;
q1.push(temp1);
}
}
int st,dr,med,ans = -1;
st = 1;
dr = 1e6;
while(st <= dr)
{
med = (st+dr)/2;
if(verif(med))
{
ans = med;
st = med+1;
}
else
dr = med-1;
}
printf("%d",ans);
return 0;
}