Advertisement
nikunjsoni

1284

Apr 23rd, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int minFlips(vector<vector<int>>& mat) {
  4.         int start=0, n=mat.size(), m=mat[0].size();
  5.         int dx[5] = {0, 1, -1, 0, 0};
  6.         int dy[5] = {0, 0, 0, 1, -1};
  7.        
  8.         for(int i=0; i<n; i++)
  9.             for(int j=0; j<m; j++)
  10.                 start |= (mat[i][j] << (i*m+j));
  11.        
  12.         queue<pair<int, int>> q;
  13.         bool vis[(1<<n*m)+1];
  14.         memset(vis, false, sizeof(vis));
  15.        
  16.         // Push the start element in queue;
  17.         q.push({start, 0});
  18.         vis[start] = true;
  19.        
  20.         while(!q.empty()){
  21.             pair<int, int> p = q.front();
  22.             q.pop();
  23.            
  24.             // If zero matrix found.
  25.             if(!p.first) return p.second;
  26.            
  27.             // Flip each bit to get next state of matrix;
  28.             for(int i=0; i<n; i++)
  29.                 for(int j=0; j<m; j++){
  30.                     int next = p.first;
  31.                     for(int k=0; k<5; k++){
  32.                         int x = i+dx[k], y = j+dy[k];
  33.                         if(x>=0 && x<n && y>=0 && y<m)
  34.                             next ^= (1<<(x*m+y));
  35.                     }
  36.                     // If next state is not visited, insert in queue.
  37.                     if(!vis[next]){
  38.                         vis[next] = true;
  39.                         q.push({next, p.second+1});
  40.                     }
  41.                 }
  42.         }
  43.         return -1;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement