Cod sursa(job #2633332)

Utilizator etohirseCristi Cretu etohirse Data 7 iulie 2020 11:07:43
Problema Barbar Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.47 kb
#include <bits/stdc++.h>
using namespace std;

const int mxN=1e3+5;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int n, m, ans, startx, starty, stopx, stopy, mat[mxN][mxN];
char a[mxN][mxN];
bool viz[mxN][mxN];
queue<pair<int,int>>cords;

bool ok(int i, int j){
	return i&&j&&i<=n&&j<=m&&viz[i][j]==0;
}
void Lee(){
	while(!cords.empty()){
		int i = cords.front().first;
		int j = cords.front().second;
		cords.pop();
		viz[i][j]=1;
		for(int k=0; k<4; ++k){
			int ni = i + dx[k];
			int nj = j + dy[k];
			if(ok(ni,nj)&&!mat[ni][nj]&&a[ni][nj]!='*'){
				mat[ni][nj]=1+mat[i][j];
				cords.push({ni,nj});
			}
		}
	}
}

bool verif(int mb){
	memset(viz,0,sizeof viz);
	queue<pair<int,int>>q;
	q.push({startx,starty});
	while(!q.empty()){
		int i = q.front().first;
		int j = q.front().second;
		q.pop();
		viz[i][j]=1;
		for(int k=0; k<4; ++k){
			int ni = i + dx[k];
			int nj = j + dy[k];
			if(ok(ni,nj)&&mat[ni][nj]>=mb){
				if(ni==stopx&&nj==stopy) return true;
				q.push({ni,nj});
			}
		}
	}
	return false;
}

int main(){
	ifstream cin("barbar.in");
	ofstream cout("barbar.out");
	cin >> n >> m;
	for(int i=1; i<=n; ++i)
		for(int j=1; j<=m; ++j){
			cin >> a[i][j];
			if(a[i][j]=='I') startx=i, starty=j;
			else if(a[i][j]=='O') stopx=i, stopy=j;
			else if(a[i][j]=='D') cords.push({i,j});
		}
	Lee();
	int lb=0, rb=mat[stopx][stopy];
	while(lb<=rb){
		int mb=(lb+rb)/2;
		if(verif(mb)){
			if(mb>ans) ans=mb;
			lb=mb+1;
		}
		else 
			rb=mb-1;
	}
	if(ans) cout<<ans;
	else cout<< -1;
}