#include "bits/stdc++.h"
using namespace std;
int n,m,bx,by,sx,sy,tx,ty;
vector< vector< char >> a;
map < pair < pair < int ,int > ,pair < int ,int >> ,int > dp;
int dx[ ] = { + 1 ,- 1 , 0 , 0 } ;
int dy[ ] = { 0 , 0 ,+ 1 ,- 1 } ;
bool invalid( int x,int y)
{
return min( x,y) < 0 or x>= n or y>= m or a[ x] [ y] == '#' ;
}
void add( int bx,int by,int sx,int sy,queue < pair < pair < int ,int > ,pair < int ,int >>> & q,int dist)
{
if ( invalid( bx,by) or invalid( sx,sy) or dp.find ( { { bx,by} ,{ sx,sy} } ) ! = dp.end ( ) ) return ;
q.push ( { { bx,by} ,{ sx,sy} } ) ;
dp[ { { bx,by} ,{ sx,sy} } ] = dist;
}
class Solution
{
public :
int minPushBox( vector< vector< char >> & grid)
{
a= grid;
dp.clear ( ) ;
n= a.size ( ) ,m= a[ 0 ] .size ( ) ;
for ( int i= 0 ; i< n; i++ )
for ( int j= 0 ; j< m; j++ )
if ( a[ i] [ j] == 'B' ) bx= i,by= j;
else if ( a[ i] [ j] == 'S' ) sx= i,sy= j;
else if ( a[ i] [ j] == 'T' ) tx= i,ty= j;
queue < pair < pair < int ,int > ,pair < int ,int >>> cur;
add( bx,by,sx,sy,cur,0 ) ;
while ( not cur.empty ( ) )
{
queue < pair < pair < int ,int > ,pair < int ,int >>> nxt;
while ( not cur.empty ( ) )
{
auto pp= cur.front ( ) ;
cur.pop ( ) ;
int dist= dp[ pp] ;
auto box= pp.first ;
auto shopkeeper= pp.second ;
if ( box.first == tx and box.second == ty) return dist;
for ( int k= 0 ; k< 4 ; k++ )
{
int nsx= shopkeeper.first + dx[ k] ,nsy= shopkeeper.second + dy[ k] ;
if ( invalid( nsx,nsy) ) continue ;
if ( nsx== box.first and nsy== box.second )
{
if ( invalid( box.first + dx[ k] ,box.second + dy[ k] ) ) continue ;
add( box.first + dx[ k] ,box.second + dy[ k] ,nsx,nsy,nxt,dist+ 1 ) ;
}
else add( box.first ,box.second ,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