Seawolf 发表于 2020-8-3 09:05:31

Leetcode 1536. Minimum Swaps to Arrange a Binary Grid

Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.

A grid is said to be valid if all the cells above the main diagonal are zeros.

Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.

The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).



Example 1:


Input: grid = [,,]
Output: 3
Example 2:


Input: grid = [,,,]
Output: -1
Explanation: All rows are similar, swaps have no effect on the grid.
Example 3:


Input: grid = [,,]
Output: 0


Constraints:

n == grid.length
n == grid.length
1 <= n <= 200
grid is 0 or 1

class Solution:
    def minSwaps(self, grid: List]) -> int:
      zeros =
      result = 0
      for i in range(len(grid)):
            count = 0
            for j in range(len(grid) - 1, -1, -1):
                if grid != 0:
                  break
                count += 1
            zeros = count
      
      n = len(grid)
      for i in range(len(grid)):
            target = n - i - 1
            for j in range(i, len(grid) + 1):
               
                if j < n and zeros >= target:
                  break
            if j == n:
                return -1
            result += j - i
            temp = zeros
            for k in range(j, i, -1):
                zeros = zeros
            zeros = temp
      return result
页: [1]
查看完整版本: Leetcode 1536. Minimum Swaps to Arrange a Binary Grid