Skip to content

Latest commit

 

History

History
33 lines (31 loc) · 896 Bytes

1536.md

File metadata and controls

33 lines (31 loc) · 896 Bytes

1536. Minimum Swaps to Arrange a Binary Grid

Solution 1 (time O(n^2), space O(n))

class Solution(object):
    def minSwaps(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n = len(grid)
        pos = [-1 for _ in range(n)]
        for i in range(n):
            for j in range(n - 1, -1, -1):
                if grid[i][j] == 1:
                    pos[i] = j
                    break
        ans = 0
        for i in range(n):
            k = -1
            for j in range(i, n):
                if pos[j] <= i:
                    ans += (j - i)
                    k = j
                    break
            if k != -1:
                for j in range(k, i, -1):
                    pos[j], pos[j - 1] = pos[j - 1], pos[j]
            else:
                return -1
        return ans