Leetcode 1536. Minimum Swaps to Arrange a Binary Grid (python)

题目

Leetcode 1536. Minimum Swaps to Arrange a Binary Grid (python)_第1张图片

解法:

将2D问题转化为1D,然后贪心的移动

class Solution:
    def minSwaps(self, grid: List[List[int]]) -> int:
        n = len(grid)
        # take this as a 1-d problem,count the continues 0 from the end in every row. What we need to do is to put the rows at the correct posistion. 
        zero_count = []
        for i in range(n):
            count = 0
            for j in range(n-1,-1,-1):
                if grid[i][j]:
                    break
                count += 1
            zero_count.append(count)
        
        # for ith from the first row to the last, we greedyly find the satisfied row to put at the ith position. When i is at the end, we have placed all the rows at correct position
        # moves counts the total swaps needed
        moves = 0
        for i in range(n):
            if zero_count[i]<n-i-1:
                # i is the current row position we need to put the satisfied row
                pos = i
                # we move down until find the satisfied row
                while pos<n and zero_count[pos]<n-i-1:
                    pos += 1
                # if we can't find the satisfied row for current i, return -1
                if pos==n:
                    return -1
                # we swap the pos row with the pos-1 row until to the ith row. But here we actually only need to swap the zero_count list
                while pos>i:
                    zero_count[pos],zero_count[pos-1] = zero_count[pos-1],zero_count[pos]
                    pos -= 1
                    moves+=1
        return moves

你可能感兴趣的:(Leetcode,贪心(greedy),leetcode,python)