1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <deque>
#include <iostream>
#include <algorithm>
using namespace std;
uint64_t is_safe(vector<vector<char>> maze,uint64_t x,uint64_t y,uint64_t n,uint64_t m,vector<vector<uint64_t>> visited)
{
if(maze[x][y] != '#' && x<n && x>=0 && y<m && y>=0 && visited[x][y] == 0)
return 1;
else return 0;
}
int main() {
uint64_t n,m;
cin >> n >> m;
vector<vector<char>> maze (n,vector<char>(m));
uint64_t initi_x ;
uint64_t initi_y ;
uint64_t end_x ;
uint64_t end_y ;
for (uint64_t i = 0; i < n; i++)
{
for (uint64_t j = 0; j < m; j++)
{
char content;
cin >> content;
if (content == 'A')
initi_x = i,initi_y = j;
if (content == 'B')
end_x = i,end_y = j;
maze[i][j] = content;
}
}
vector<deque<uint64_t>> queue(2);
vector<vector<uint64_t>> visited (n+1,vector<uint64_t>(m+1));
vector<vector<uint64_t>> distance(n+1,vector<uint64_t>(m+1));
uint64_t max = 0;
bool flag = false;
queue[0].push_front(initi_x),queue[1].push_front(initi_y);
visited[initi_x][initi_y] = 1;
while(!(queue[0].empty() && queue[1].empty()))
{
auto from_x = queue[0].front(); auto from_y = queue[1].front();
if(is_safe(maze,from_x+1,from_y,n,m,visited))
{
visited[from_x+1][from_y] = 1;
distance[from_x+1][from_y] = distance[from_x][from_y]+1;
if(from_x+1 == end_x && from_y == end_y) {flag = true;max = distance[from_x+1][from_y]; break;}
queue[0].push_back(from_x+1),queue[1].push_back(from_y);
}
if(is_safe(maze,from_x-1,from_y,n,m,visited))
{
visited[from_x-1][from_y] = 1;
distance[from_x-1][from_y] = distance[from_x][from_y]+1;
if(from_x-1 == end_x && from_y == end_y) {flag = true;max = distance[from_x-1][from_y]; break;}
queue[0].push_back(from_x-1),queue[1].push_back(from_y);
}
if(is_safe(maze,from_x,from_y+1,n,m,visited))
{
visited[from_x][from_y+1] = 1;
distance[from_x][from_y+1] = distance[from_x][from_y]+1;
if(from_x == end_x && from_y+1 == end_y) {flag = true;max = distance[from_x][from_y+1]; break;}
queue[0].push_back(from_x),queue[1].push_back(from_y+1);
}
if(is_safe(maze,from_x,from_y-1,n,m,visited))
{
visited[from_x][from_y-1] = 1;
distance[from_x][from_y-1] = distance[from_x][from_y]+1;
if(from_x == end_x && from_y-1 == end_y) {flag = true;max = distance[from_x][from_y-1]; break;}
queue[0].push_back(from_x),queue[1].push_back(from_y-1);
}
queue[0].pop_front(); queue[1].pop_front();
}
if(flag == false) {cout << "IMPOSSIBLE" ;}
else {cout << max ;}
return 0;
}
|