Pagini recente » Cod sursa (job #1278722) | Cod sursa (job #3121478) | Cod sursa (job #28283) | Cod sursa (job #2035996) | Cod sursa (job #3236393)
#include <bits/stdc++.h>
#define int long long
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
int mat[2005][2005], n, m;
queue<pair<int, int>> q;
pair<int, int> pozi, pozf;
bool ok[2005][2005];
void dfs(pair<int, int> poz, int nivel)
{
int i = poz.first;
int j = poz.second;
//cout<<i<<" "<<j<<" "<<ok[i+1][j]<<" "<<mat[i+1][j]<<'\n';
ok[i][j]=1;
if(ok[i+1][j] == 0 && mat[i+1][j]>=nivel && i+1<=n) dfs({i+1, j}, nivel);
if(ok[i][j+1] == 0 && mat[i][j+1]>=nivel && j+1<=m) dfs({i, j+1}, nivel);
if(ok[i-1][j] == 0 && mat[i-1][j]>=nivel && i-1>=1) dfs({i-1, j}, nivel);
if(ok[i][j-1] == 0 && mat[i][j-1]>=nivel && j-1>=1) dfs({i, j-1}, nivel);
}
void reset()
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
ok[i][j]=0;
}
void afis(int nivel)
{
cout<<nivel<<'\n';
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)
cout<<ok[i][j];
cout<<'\n';
}
cout<<'\n';
}
bool parcurgere(int nivel)
{
reset();
dfs(pozi, nivel);
//afis(nivel);
if(ok[pozf.first][pozf.second]==1) return true;
else return false;
}
int32_t main()
{
ifstream cin("barbar.in");
ofstream cout("barbar.out");
char ch;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>ch;
if(ch=='D') mat[i][j]=1, q.push({i, j});
else if(ch=='*') mat[i][j]=-1;
else if(ch=='I') pozi = {i, j};
else if(ch=='O') pozf = {i, j};
else mat[i][j] = 0;
}
}
while(q.empty()==false)
{
int i = q.front().first;
int j = q.front().second;
q.pop();
//cout<<i<<" "<<j<<'\n';
if(mat[i+1][j]==0 && i+1<=n) mat[i+1][j] = mat[i][j] + 1, q.push({i+1, j});
if(mat[i][j+1]==0 && j+1<=m) mat[i][j+1] = mat[i][j] + 1, q.push({i, j+1});
if(mat[i-1][j]==0 && i-1>=1) mat[i-1][j] = mat[i][j] + 1, q.push({i-1, j});
if(mat[i][j-1]==0 && j-1>=1) mat[i][j-1] = mat[i][j] + 1, q.push({i, j-1});
}
int maxx=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
maxx = max(maxx, mat[i][j]);//, cout<<mat[i][j]<<" ";
//cout<<'\n';
}
int st=1, dr=maxx;
while(st<dr)
{
int mij=(st+dr)/2;
//cout<<st<<" "<<dr<<" "<<mij<<'\n';
if(parcurgere(mij) == true) st = mij + 1;
else if(parcurgere(mij) == false) dr = mij - 1;
}
cout<<(st+dr)/2-1;
return 0;
}