Pagini recente » Cod sursa (job #322032) | Cod sursa (job #2964780) | Cod sursa (job #258835) | Cod sursa (job #991132) | Cod sursa (job #796049)
Cod sursa(job #796049)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
char v[1011][1011];
int cost[1011][1011];
int finalx=0,finaly=0;
int startx=0,starty=0;
int r,c;
bool visited[1011][1010];
bool checkPath(int x,int y,int expectedCost)
{
if ((x<0) ||(x>r)) return false;
if ((y<0) ||(y>c)) return false;
if (cost[x][y] == 0 ) return false;
if (cost[x][y] < expectedCost) return false;
if (visited[x][y]) return false;
if ((x==finalx)&&(y==finaly))
{
return true;
}
visited[x][y] = true;
return checkPath(x-1,y,expectedCost) ||checkPath(x+1,y,expectedCost)||checkPath(x,y+1,expectedCost)||checkPath(x,y-1,expectedCost);
}
int main()
{
int res=-1;
fin >> r >> c;
char endline;
//fin >> endline;
for (int i=0; i<r; i++)
{
for (int j=0; j<c; j++)
{
fin >> v[i][j];
}
//fin >> endline;
}
for (int i=0; i<r; i++)
for (int j=0; j<c; j++)
cost[i][j]=1000000;
vector< pair<int , int > > updPoints;
vector< pair<int , int > > updPointsNew;
updPoints.clear();
for (int i=0; i<r; i++)
{
for (int j=0; j<c; j++)
{
//cout << v[i][j];
if (v[i][j] == 'D')
{
updPoints.push_back(make_pair(i,j));
cost[i][j]=0;
}
if (v[i][j] == '*')
{
cost[i][j]=-1;
}
if (v[i][j] == 'O')
{
finalx = i;
finaly = j;
}
if (v[i][j] == 'I')
{
startx = i;
starty = j;
}
}
//cout << endl;
}
//cout <<"D number:"<< updPoints.size()<<endl;
bool found=true;
while (found)
{
found = false;
updPointsNew.clear();
for (int i=0; i<updPoints.size(); i++)
{
for (int j=0; j<4; j++)
{
int x= updPoints[i].first;
int y= updPoints[i].second;
int dx=x;
int dy=y;
if (j==0) dx--;
if (j==1) dx++;
if (j==2) dy--;
if (j==3) dy++;
if (dx>r||dx<0||dy<0||dy>c) continue;
if (cost[dx][dy] > cost[x][y]+1)
{
cost[dx][dy] = cost[x][y]+1;
updPointsNew.push_back(make_pair(dx,dy));
found = true;
}
}
}
swap(updPointsNew,updPoints);
}
int rr=1000000;
int ll=0;
while (ll<rr)
{
int mm = (rr + ll) / 2 + 1;
for (int i=0; i<r; i++)
{
for (int j=0; j<c; j++)
{
visited[i][j] =false;
// fout << cost[i][j]<< " ";
}
//fout << endl;
}
//cout << "rr:"<<rr<<","<<"ll:"<<ll<<endl;
if (checkPath(startx,starty,mm))
{
//cout << "check ok" << mm <<endl;
res=mm;
ll= mm+1;
}
else
{
//cout << "check failed"<< mm << endl;
rr= mm-1;
}
swap(updPointsNew,updPoints);
}
fout << res;
}