Pagini recente » Cod sursa (job #1549782) | Cod sursa (job #1115226) | Cod sursa (job #501377) | Cod sursa (job #1256581) | Cod sursa (job #2665284)
#include <fstream>
#include <queue>
constexpr auto max_size = 1005;
using namespace std;
ifstream fin("barbar.in");
ofstream fout("barbar.out");
int r, c;
char current_line[max_size] = { NULL };
int dragons_distances[max_size][max_size];
bool viz[max_size][max_size];
pair<int, int> beg_pos;
pair<int, int> end_pos;
queue<pair<int, int>> bfs_queue;
int dx[] = { -1, 0, 1, 0 };
int dy[] = { 0, -1, 0, 1 };
class comparison_class {
public:
bool operator() (pair<int, int> a, pair<int, int> b) {
return dragons_distances[a.first][a.second] < dragons_distances[b.first][b.second];
}
};
priority_queue<pair<int, int>, vector<pair<int, int>>, comparison_class> visit_queue;
bool valid_pos(pair<int, int> pos)
{
if (pos.first >= 0 && pos.first < r &&
pos.second >= 0 && pos.second < c)
if (dragons_distances[pos.first][pos.second] != -2)
return true;
return false;
}
int main()
{
fin >> r >> c;
for (auto i = 0; i < r; i++)
{
fin >> current_line;
for (auto j = 0; j < c; j++)
{
const auto chr = current_line[j];
switch (chr)
{
case '.':
dragons_distances[i][j] = -1;
break;
case '*':
dragons_distances[i][j] = -2;
break;
case 'D':
dragons_distances[i][j] = 0;
bfs_queue.push(make_pair(i, j));
break;
case 'I':
dragons_distances[i][j] = -1;
beg_pos = make_pair(i, j);
break;
case 'O':
dragons_distances[i][j] = -1;
end_pos = make_pair(i, j);
break;
default: ;
}
}
}
while (!bfs_queue.empty())
{
auto& crt_node = bfs_queue.front();
bfs_queue.pop();
const auto dist = dragons_distances[crt_node.first][crt_node.second];
for (auto i = 0; i < 4; i++)
{
auto new_pos = make_pair(crt_node.first + dx[i], crt_node.second + dy[i]);
if (valid_pos(new_pos))
{
if (dragons_distances[new_pos.first][new_pos.second] == -1)
{
dragons_distances[new_pos.first][new_pos.second] = dist + 1;
bfs_queue.push(new_pos);
}
}
}
}
auto result = dragons_distances[beg_pos.first][beg_pos.second];
visit_queue.push(beg_pos);
viz[beg_pos.first][beg_pos.second] = true;
while (!visit_queue.empty())
{
auto crt_node = visit_queue.top();
visit_queue.pop();
auto dist = dragons_distances[crt_node.first][crt_node.second];
result = min(dist, result);
if (crt_node == end_pos)
break;
for (auto i = 0; i < 4; i++)
{
auto new_pos = make_pair(crt_node.first + dx[i], crt_node.second + dy[i]);
if (valid_pos(new_pos))
{
if (!viz[new_pos.first][new_pos.second])
{
viz[new_pos.first][new_pos.second] = true;
visit_queue.push(new_pos);
}
}
}
}
fout << result;
return 0;
}