akashtadwai

MinCostPath

Aug 18th, 2021 (edited)
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #define ar array<int,2>
  2. map<pair<int,int>,char>mp{{{1,0},'R'},{{0,1},'U'},{{-1,0},'L'},{{0,-1},'D'}};
  3. vector<array<int,2> >dirs{{1,0},{0,1},{-1,0},{0,-1}};
  4. int bfs(vector<vector<char>>&g){
  5.     int n=g.size(),m=g[0].size();
  6.     auto isvalid = [&] (int x, int y)-> bool {
  7.         return x>=0 and x<n and y>=0 and y<m;
  8.     };
  9.     deque<ar>q;
  10.     vector<vector<int>>dis(n,vector<int>(m,n+m));
  11.     vector<vector<bool>>vis(n,vector<bool>(m,false));
  12.     q.push_front({0,0});
  13.     dis[0][0]=0;
  14.     vis[0][0]=true;
  15.     while(!q.empty()){
  16.         auto [i,j] = q.front();
  17.         q.pop_front();
  18.         for(auto dir:dirs){
  19.             int ni = i+dir[0],nj=j+dir[1];
  20.             if(isvalid(ni,nj) and !vis[ni][nj] and mp[make_pair(dir[0],dir[1])] == g[i][j] and dis[ni][nj]>dis[i][j]) {
  21.                 dis[ni][nj] = dis[i][j];
  22.                 q.push_front({ni,nj});
  23.             }
  24.  
  25.             if(isvalid(ni,nj) and !vis[ni][nj] and mp[make_pair(dir[0],dir[1])] != g[i][j] and dis[ni][nj]>dis[i][j] +1 ) {
  26.                 dis[ni][nj] = dis[i][j]+1;
  27.                 q.push_back({ni,nj});
  28.             }
  29.         }
  30.     }
  31.     return dis[n-1][m-1];
  32. }
  33. int Solution::solve(int A, int B, vector<string> &C) {
  34.     vector<vector<char>>g(A,vector<char>(B));
  35.     for(int i=0;i<A;i++){
  36.         for(int j=0;j<B;j++) {
  37.             g[i][j] = C[i][j];
  38.         }
  39.     }
  40.    return bfs(g);
  41. }
  42.  
Add Comment
Please, Sign In to add comment