1536. Minimum Swaps to Arrange a Binary Grid

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 1536

class Solution:
    def minSwaps(self, grid: List[List[int]]) -> int:
        n = len(grid)
        pos = [-1] * n
        for i in range(n):
            for j in range(n - 1, -1, -1):
                if grid[i][j] == 1:
                    pos[i] = j
                    break
        res = 0
        for i in range(n):
            k = -1
            for j in range(i, n):
                if pos[j] <= i:
                    res += j - i
                    k = j
                    break
            if k == -1:
                return -1
            while k > i:
                pos[k], pos[k - 1] = pos[k - 1], pos[k]
                k -= 1
        return res