Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int INF = 1e9;
- const int N = 5e2 + 10;
- const int M = 500 + 10;
- struct Data{
- int dis, i, j, J, B, P;
- };
- int n, m;
- char ar[N][M];
- int Dis[N][M][2][2][2];
- bool vs[N][M][2][2][2];
- int di[] = {0, 0, 1, -1};
- int dj[] = {1, -1, 0, 0};
- bool pst(int i, int j){
- return i >= 1 and i <= n and j >= 1 and j <= m;
- }
- bool check(int i, int j, int J, int B, int P){
- if(ar[i][j] == '.'
- or ar[i][j] == 'j'
- or ar[i][j] == 'b'
- or ar[i][j] == 'p'
- or ar[i][j] == 'S'
- or ar[i][j] == 'E')
- return true;
- if(ar[i][j] == 'J' and J) return true;
- else if(ar[i][j] == 'B' and B) return true;
- else if(ar[i][j] == 'P' and P) return true;
- return false;
- }
- int main(){
- scanf("%d%d", &n, &m);
- int si = -1, sj = -1, ei = -1, ej = -1;
- for(int i=1;i<=n;i++){
- for(int j=1;j<=m;j++){
- scanf(" %c", &ar[i][j]);
- if(ar[i][j] == 'S'){
- si = i;
- sj = j;
- }
- else if(ar[i][j] == 'E'){
- ei = i;
- ej = j;
- }
- }
- }
- for(int i=1;i<=n;i++){
- for(int j=1;j<=m;j++){
- for(int J=0;J<=1;J++){
- for(int B=0;B<=1;B++){
- for(int P=0;P<=1;P++){
- Dis[i][j][J][B][P] = INF;
- vs[i][j][J][B][P] = false;
- }
- }
- }
- }
- }
- queue <Data> q;
- Dis[si][sj][0][0][0] = 0;
- q.push({Dis[si][sj][0][0][0], si, sj, 0, 0, 0});
- while(!q.empty()){
- int d = q.front().dis;
- int ui = q.front().i;
- int uj = q.front().j;
- int j = q.front().J;
- int b = q.front().B;
- int p = q.front().P;
- q.pop();
- if(vs[ui][uj][j][b][p])
- continue;
- vs[ui][uj][j][b][p] = true;
- if(ui == ei and uj == ej){
- printf("%d", d);
- return 0;
- }
- for(int dij=0;dij<4;dij++){
- int vi = ui + di[dij];
- int vj = uj + dj[dij];
- if(!pst(vi, vj)) continue;
- int jj = j, bb = b, pp = p;
- if(ar[vi][vj] == 'j') jj = 1;
- else if(ar[vi][vj] == 'b') bb = 1;
- else if(ar[vi][vj] == 'p') pp = 1;
- if(check(vi, vj, jj, bb, pp) and !vs[vi][vj][jj][bb][pp] and d + 1 < Dis[vi][vj][jj][bb][pp]){
- Dis[vi][vj][jj][bb][pp] = d + 1;
- q.push({Dis[vi][vj][jj][bb][pp], vi, vj, jj, bb, pp});
- }
- }
- }
- printf("-1");
- return 0;
- }
- /*
- 5 5
- j...p
- .....
- .S#P.
- .#EB.
- PbJ..
- */
Add Comment
Please, Sign In to add comment