Pagini recente » Cod sursa (job #2453482) | Cod sursa (job #2579159) | Cod sursa (job #2882000) | Cod sursa (job #3244756) | Cod sursa (job #2135531)
#include <fstream>
#include <queue>
using namespace std;
#define Max 1001
int a[Max][Max], d[Max][Max];
int x1,y1,x2,y2,R,C;
queue<int> qx,qy;
int Lee(int k)
{
int i,j,p;
while (!qx.empty()) qx.pop(); while (!qy.empty()) qy.pop();
// queue<int> qx,qy;
for (i=1;i<=R;i++)
for (j=1;j<=C;j++)
if(a[i][j]>0) a[i][j]=0;
qx.push(x1); qy.push(y1); a[x1][y1]=1;
while (!qx.empty()) {
i=qx.front(); qx.pop(); j=qy.front(); qy.pop();
p=a[i][j];
if (a[i][j+1]==0 && d[i][j+1]>=k) {a[i][j+1]=p+1; qx.push(i); qy.push(j+1);}
if (a[i-1][j]==0 && d[i-1][j]>=k) {a[i-1][j]=p+1; qx.push(i-1); qy.push(j);}
if (a[i][j-1]==0 && d[i][j-1]>=k) {a[i][j-1]=p+1; qx.push(i); qy.push(j-1);}
if (a[i+1][j]==0 && d[i+1][j]>=k) {a[i+1][j]=p+1; qx.push(i+1); qy.push(j);}
if (a[x2][y2]>0) return 1;
}
return 0;
}
int main()
{
int i,j,p,k=0,mx=0;
char s[Max+1];
// queue<int> qx,qy;
ifstream f1("barbar.in"); ofstream f2("barbar.out");
f1>>R>>C;
for (i=0;i<=R+1;i++) a[i][0]=a[i][C+1]=d[i][0]=d[i][C+1]=-1;
for (j=0;j<=C+1;j++) a[0][j]=a[R+1][j]=d[0][j]=d[R+1][j]=-1;
for (i=1;i<=R;i++) {
f1>>s;
for (j=0;j<C;j++) {
if (s[j]=='*') {a[i][j+1]=-1; d[i][j+1]=-1;}
if (s[j]=='I') {x1=i; y1=j+1;}
if (s[j]=='O') {x2=i; y2=j+1;}
if (s[j]=='D') {d[i][j+1]=1; qx.push(i); qy.push(j+1);}
}
}
while (!qx.empty()) {
i=qx.front(); qx.pop(); j=qy.front(); qy.pop();
p=d[i][j];
if (d[i][j+1]==0) {d[i][j+1]=p+1; qx.push(i); qy.push(j+1);}
if (d[i-1][j]==0){d[i-1][j]=p+1; qx.push(i-1); qy.push(j);}
if (d[i][j-1]==0) {d[i][j-1]=p+1; qx.push(i); qy.push(j-1);}
if (d[i+1][j]==0) {d[i+1][j]=p+1; qx.push(i+1); qy.push(j);}
}
for (i=1;i<=R;i++)
for (j=1;j<=C;j++)
if (d[i][j]>mx) mx=d[i][j];
for (i=1;i<=R;i++)
for (j=1;j<=C;j++)
if (d[i][j]==0) d[i][j]=mx+1;
while (k==0 && mx>=0) {
k=Lee(mx);
mx--;
}
if (k) f2 << mx;
else f2 << -1;
return 0;
}