LeetCode1536. 排布二进制网格的最少交换次数

我主要是参考了这篇题解

class Solution {
    
    
public:
    int minSwaps(vector<vector<int>>& grid) {
    
    
        vector<int> a;
        int n = grid.size();
        for (int i = 0;i < n;i++)
        {
    
    
            int temp = 0;
            for (int j = n - 1; j >= 0;j--)
            {
    
    
                if (grid[i][j] == 0)
                {
    
    
                    temp++;
                }
                else
                {
    
    
                    break;
                }
            }
            a.push_back(temp);
        }

        int count = 0;
        for (int i = 0; i < n - 1;i++)
        {
    
    
            if (a[i] >= n - 1 - i)
            {
    
    
                continue;
            }
            else
            {
    
    
                int j = i;
                for (;j < n;j++)
                {
    
    
                    if (a[j] >= n - i - 1)
                    {
    
    
                        break;
                    }
                }
                if (j == n)
                {
    
    
                    return -1;
                }
                for (;j > i;j--)
                {
    
    
                    swap(a[j], a[j - 1]);
                    count++;
                }
            }
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32862515/article/details/107783890