Pagini recente » Cod sursa (job #2276955) | Cod sursa (job #2958574)
#include <fstream>
#include <queue>
#include <climits>
#include <cstring>
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
const short vec_len = 1005;
struct pos
{
short l;
short c;
};
short n, m;
short dmap[vec_len][vec_len];
short dirl[] = {-1, 0, 1, 0}, dirc[] = {0, 1, 0, -1};
pos tstart, texit;
queue<pos> drag;
queue<pos> path;
bool check(short l, short c)
{
if (l < 1 || l > n)
return false;
if (c < 1 || c > m)
return false;
return true;
}
void dragLee()
{
while (!drag.empty())
{
pos curr = drag.front();
drag.pop();
short nl = curr.l, nc = curr.c;
for (short i = 0; i < 4; i++)
{
nl = curr.l + dirl[i];
nc = curr.c + dirc[i];
if (check(nl, nc) && dmap[nl][nc] == 0)
{
dmap[nl][nc] = dmap[curr.l][curr.c] + 1;
drag.push(pos{nl, nc});
}
}
}
}
short res[vec_len][vec_len];
void pathLee()
{
path.push(pos{tstart.l, tstart.c});
res[tstart.l][tstart.c] = dmap[tstart.l][tstart.c];
while (!path.empty())
{
pos curr = path.front();
path.pop();
short nl, nc;
for (short i = 0; i < 4; i++)
{
nl = curr.l + dirl[i];
nc = curr.c + dirc[i];
if (check(nl, nc) && res[nl][nc] > -1 && res[nl][nc] < min(res[curr.l][curr.c], dmap[nl][nc]))
{
res[nl][nc] = min(res[curr.l][curr.c], dmap[nl][nc]);
if (nl == texit.l && nc == texit.c)
continue;
else
path.push(pos{nl, nc});
}
}
}
if (res[texit.l][texit.c] == 0)
fout << "-1";
else
fout << res[texit.l][texit.c];
}
int main()
{
fin.tie(NULL);
fout.tie(NULL);
ios::sync_with_stdio(false);
fin >> n >> m;
char x;
for (short i = 1; i <= n; i++)
for (short j = 1; j <= m; j++)
{
fin >> x;
if (x == 'D')
drag.push(pos{i, j}), dmap[i][j] = 0;
else if (x == 'I')
tstart = pos{i, j};
else if (x == '*')
dmap[i][j] = -1;
else if (x == 'O')
texit = pos{i, j};
}
dragLee();
pathLee();
return 0;
}