1536. Minimum Swaps to Arrange a Binary Grid
Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: int minSwaps(vector<vector<int>>& A) { vector<int> counter; int n = A.size(), m = A[0].size(); for(int i = 0; i < n; i++) { int cnt = 0; for(int j = m - 1; j >= 0; j--) { if(A[i][j] == 0) cnt++; else break; } counter.push_back(cnt); } int req = m - 1, res = 0; for(int i = 0; req; i++,req--) { int find = -1; for(int j = i; j < n; j++) { if(counter[j] >= req) { find = j; break; } } if(find == -1) return -1; res += find - i; while(find != i) { swap(counter[find - 1], counter[find]); find--; } } return res; } };
|