Pagini recente » Cod sursa (job #1349206) | Cod sursa (job #1116334) | Istoria paginii runda/abcqq/clasament | Cod sursa (job #2131525) | Cod sursa (job #2812467)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
queue <pair<int, int> > q;
int vis[1005][1005], vis1[1005][1005];
char a[1005][1005];
int v[1005][1005];
int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
pair<int, int> poz;
void bfs(pair<int, int> poz, int n, int m)
{
int x = poz.first;
int y = poz.second;
vis[x][y] = true;
while (!q.empty())
{
poz = q.front();
x = poz.first;
y = poz.second;
q.pop();
for (int k = 0; k < 4; k++)
{
int x1 = x + dx[k];
int y1 = y + dy[k];
if (x1 >= 1 and x1 <= n and y1 >= 1 and y1 <= m and a[x1][y1] != 'D' and a[x1][y1] != '*' and !vis[x1][y1])
{
v[x1][y1] = v[x][y] + 1;
vis[x1][y1] = true;
poz = make_pair(x1, y1);
q.push(poz);
}
if (x1 >= 1 and x1 <= n and y1 >= 1 and y1 <= m and a[x1][y1] == '*' and !vis[x1][y1])
{
v[x1][y1] = -1;
vis[x1][y1] = true;
}
}
}
}
void drum(pair<int, int> paf, int n, int m)
{
pair<int, int> plecare = paf;
int ip = paf.first;
int jp = paf.second;
int minn = v[ip][jp];
vis1[ip][jp] = true;
while (!q.empty())
{
bool ok = 0;
paf = q.front();
int ip = paf.first;
int jp = paf.second;
q.pop();
for (int k = 0; k < 4; k++)
{
int x1 = ip + dx[k];
int y1 = jp + dy[k];
if (x1 >= 1 and x1 <= n and y1 >= 1 and y1 <= m and v[x1][y1] >= minn and !vis1[x1][y1])
{
ok = 1;
vis1[x1][y1] = true;
paf = make_pair(x1, y1);
q.push(paf);
if (a[x1][y1] == 'O')
while (!q.empty())
q.pop();
}
}
if (ok == 0)
{
minn--;
while (!q.empty())
q.pop();
q.push(plecare);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
vis1[i][j] = false;
}
}
}
}
int main()
{
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int n, m, ip, jp, minn;
pair<int, int> paf;
fin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
fin >> a[i][j];
if (a[i][j] == 'I')
ip = i, jp = j;
if (a[i][j] == 'D')
{
v[i][j] = 0;
poz = make_pair(i, j);
q.push(poz);
}
}
}
bfs(q.front(), n, m);
minn = v[ip][jp];
paf = make_pair(ip, jp);
q.push(paf);
drum(paf, n, m);
fout << minn;
return 0;
}