LC 1536. Minimum Swaps to Arrange a Binary Grid

link

prove: @interviewrecipes https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/discuss/768076/Min-Adjacent-Swaps-to-Sort-the-array-of-INTEGERS

class Solution {
public:
    int minSwaps(vector<vector<int>>& grid) {
        int n=grid.size();
        vector<int> arr(n);
        for(int i=0;i<n;i++){
            int j=n-1;
            int cnt=0;
            while(j>=0 && grid[i][j]==0){
                cnt++;
                j--;
            }
            arr[i]=cnt;
        }
        int res=0;
        
        for(int i=0;i<n;i++){
            if(arr[i]<n-i-1){
                int j=i+1;
                while(j<n && arr[j]<n-i-1) j++;
                if(j==n) return -1;
                for(int k=j;k>i;k--){
                    res++;
                    swap(arr[k],arr[k-1]);
                }
            }
        }
        return res;
    }
};
posted @ 2020-08-04 11:05  feibilun  阅读(161)  评论(0编辑  收藏  举报