-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1536.cpp
More file actions
27 lines (27 loc) · 791 Bytes
/
1536.cpp
File metadata and controls
27 lines (27 loc) · 791 Bytes
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
class Solution {
public:
int minSwaps(vector<vector<int>>& grid) {
int n = grid.size();
vector<int> zerosCnt(n, 0);
for (int i = 0; i < n; ++i) {
int index = n - 1;
while (index >= 0 && grid[i][index] != 1) index--;
zerosCnt[i] = n - 1 - index;
}
int res = 0;
for (int i = 0; i < n; ++i) {
int target = n - 1 - i;
if (zerosCnt[i] < target) {
int j = i;
while (j < n && zerosCnt[j] < target) j++;
if (j == n) return -1;
while (j != i) {
swap(zerosCnt[j - 1], zerosCnt[j]);
j--;
res++;
}
}
}
return res;
}
};