int minimumCostPath( vector< vector< int >> & grid)
{
int n = grid.size ( ) , m = grid[ 0 ] .size ( ) ;
vector< vector< int >> cost( n,vector< int > ( m,1e9 ) ) ;
cost[ 0 ] [ 0 ] = grid[ 0 ] [ 0 ] ;
priority_queue< pair< int ,pair< int ,int >> , vector< pair< int ,pair< int ,int >>> ,
greater< pair< int ,pair< int ,int >>>> pq;
pq.push ( { cost[ 0 ] [ 0 ] ,{ 0 ,0 } } ) ;
int row[ ] = { 0 ,- 1 ,0 ,1 } ;
int col[ ] = { 1 ,0 ,- 1 ,0 } ;
while ( ! pq.empty ( ) )
{
int cst = pq.top ( ) .first ;
int i = pq.top ( ) .second .first ;
int j = pq.top ( ) .second .second ;
pq.pop ( ) ;
for ( int k= 0 ; k< 4 ; k++ )
{
int nr = i+ row[ k] ;
int nc = j+ col[ k] ;
if ( nr< 0 || nc< 0 || nr>= n || nc>= m)
continue ;
if ( cost[ nr] [ nc] > cst+ grid[ nr] [ nc] )
{
cost[ nr] [ nc] = cst+ grid[ nr] [ nc] ;
pq.push ( { cost[ nr] [ nc] ,{ nr,nc} } ) ;
}
}
}
return cost[ n- 1 ] [ m- 1 ] ;
}
ICAgIGludCBtaW5pbXVtQ29zdFBhdGgodmVjdG9yPHZlY3RvcjxpbnQ+PiYgZ3JpZCkgCiAgICB7CiAgICAgICAgaW50IG4gPSBncmlkLnNpemUoKSwgbSA9IGdyaWRbMF0uc2l6ZSgpOwogICAgICAgIAogICAgICAgIHZlY3Rvcjx2ZWN0b3I8aW50Pj4gY29zdChuLHZlY3RvcjxpbnQ+KG0sMWU5KSk7CiAgICAgICAgCiAgICAgICAgY29zdFswXVswXSA9IGdyaWRbMF1bMF07CiAgICAgICAgCiAgICAgICAgcHJpb3JpdHlfcXVldWU8cGFpcjxpbnQscGFpcjxpbnQsaW50Pj4sIHZlY3RvcjxwYWlyPGludCxwYWlyPGludCxpbnQ+Pj4sIAogICAgICAgICAgICBncmVhdGVyPHBhaXI8aW50LHBhaXI8aW50LGludD4+Pj4gcHE7CiAgICAgICAgCiAgICAgICAgcHEucHVzaCh7Y29zdFswXVswXSx7MCwwfX0pOwogICAgICAgIAogICAgICAgIGludCByb3dbXSA9IHswLC0xLDAsMX07CiAgICAgICAgaW50IGNvbFtdID0gezEsMCwtMSwwfTsKICAgICAgICAKICAgICAgICB3aGlsZSghcHEuZW1wdHkoKSkKICAgICAgICB7CiAgICAgICAgICAgIGludCBjc3QgPSBwcS50b3AoKS5maXJzdDsKICAgICAgICAgICAgaW50IGkgPSBwcS50b3AoKS5zZWNvbmQuZmlyc3Q7CiAgICAgICAgICAgIGludCBqID0gcHEudG9wKCkuc2Vjb25kLnNlY29uZDsKICAgICAgICAgICAgcHEucG9wKCk7CiAgICAgICAgICAgIAogICAgICAgICAgICBmb3IoaW50IGs9MDtrPDQ7aysrKQogICAgICAgICAgICB7CiAgICAgICAgICAgICAgICBpbnQgbnIgPSBpK3Jvd1trXTsKICAgICAgICAgICAgICAgIGludCBuYyA9IGorY29sW2tdOwogICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICBpZihucjwwIHx8IG5jPDAgfHwgbnI+PW4gfHwgbmM+PW0pIAogICAgICAgICAgICAgICAgCWNvbnRpbnVlOwogICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICBpZihjb3N0W25yXVtuY10gPiBjc3QrZ3JpZFtucl1bbmNdKQogICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgIGNvc3RbbnJdW25jXSA9IGNzdCtncmlkW25yXVtuY107CiAgICAgICAgICAgICAgICAgICAgcHEucHVzaCh7Y29zdFtucl1bbmNdLHtucixuY319KTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICAKICAgICAgICByZXR1cm4gY29zdFtuLTFdW20tMV07CiAgICB9Cg==