← Home

1536. Minimum Swaps to Arrange a Binary Grid

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
153

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1536. Minimum Swaps to Arrange a Binary Grid, the solution in this repository is mainly a greedy solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • WA
  • 104 / 129 test cases passed.
  • [[1,0,0,0,0,0],[0,1,0,1,0,0],[1,0,0,0,0,0],[1,1,1,0,0,0],[1,1,0,1,0,0],[1,0,0,0,0,0]]

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are minSwaps, maxRight.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//WA
02//104 / 129 test cases passed.
03//[[1,0,0,0,0,0],[0,1,0,1,0,0],[1,0,0,0,0,0],[1,1,1,0,0,0],[1,1,0,1,0,0],[1,0,0,0,0,0]]
04class Solution {
05public:
06    int minSwaps(vector<vector<int>>& grid) {
07        int n = grid.size();
08        
09        vector<pair<int, int>> maxRight(n);
10        
11        for(int i = 0; i < n; ++i){
12            int j;
13            for(j = n-1; j >= 0 && grid[i][j] == 0; --j){}
14            maxRight[i] = {n-1-j, i};
15        }
16        
17        /*
18        sort descending by count and then ascending by index
19        [[1,0,0,0],[1,1,1,1],[1,0,0,0],[1,0,0,0]]
20        */
21        sort(maxRight.begin(), maxRight.end(),
22            [](pair<int,int>& a, pair<int,int>& b){
23                return (a.first == b.first) ? a.second < b.second : a.first > b.first;
24            });
25        for(int i = 0; i < n; ++i){
26            if(maxRight[i].first < n-1-i) return -1;
27        }
28        
29        //now we are sure that the answer exist
30        int swaps = 0;
31        
32        for(int i = 0; i < n; ++i){
33            swaps += maxRight[i].second - i;
34            for(int j = i+1; j < n; ++j){
35                if(maxRight[j].second < maxRight[i].second){
36                    ++maxRight[j].second;
37                }
38            }
39        }
40        
41        return swaps;
42    }
43};
44
45//Greedy
46//https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/discuss/768076/Min-Adjacent-Swaps-to-Sort-the-array-of-INTEGERS-with-Proof
47//Runtime: 156 ms, faster than 100.00% of C++ online submissions for Minimum Swaps to Arrange a Binary Grid.
48//Memory Usage: 25.9 MB, less than 100.00% of C++ online submissions for Minimum Swaps to Arrange a Binary Grid.
49class Solution {
50public:
51    int minSwaps(vector<vector<int>>& grid) {
52        int n = grid.size();
53        
54        vector<int> maxRight(n);
55        
56        for(int i = 0; i < n; ++i){
57            int j;
58            for(j = n-1; j >= 0 && grid[i][j] == 0; --j){}
59            maxRight[i] = n-1-j;
60        }
61        
62        //sort descending
63        vector<int> tmp = maxRight;
64        sort(tmp.rbegin(), tmp.rend());
65        for(int i = 0; i < n; ++i){
66            if(tmp[i] < n-1-i) return -1;
67        }
68        
69        //now we are sure that the answer exist
70        int swaps = 0;
71        
72        for(int i = 0; i < n; ++i){
73            if(maxRight[i] < n-1-i){
74                //move some row up
75                int j;
76                for(j = i+1; j < n && maxRight[j] < n-1-i; ++j){}
77                
78                //jth row is what we want
79                //move jth row to ith row
80                //i,i+1,...,j-1,j -> j,i+1,i+2,...,j-1
81                int jcount = maxRight[j];
82                maxRight.erase(maxRight.begin()+j);
83                maxRight.insert(maxRight.begin()+i, jcount);
84                swaps += j-i;
85            }
86        }
87        
88        return swaps;
89    }
90};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.