鱼C论坛

 找回密码
 立即注册
查看: 2066|回复: 0

[学习笔记] Leetcode 1536. Minimum Swaps to Arrange a Binary Grid

[复制链接]
发表于 2020-8-3 09:05:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

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

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

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



  5. Example 1:
  6. Screenshot from 2020-08-02 21-04-19.png

  7. Input: grid = [[0,0,1],[1,1,0],[1,0,0]]
  8. Output: 3
  9. Example 2:
  10. Screenshot from 2020-08-02 21-04-26.png

  11. Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
  12. Output: -1
  13. Explanation: All rows are similar, swaps have no effect on the grid.
  14. Example 3:
  15. Screenshot from 2020-08-02 21-04-36.png

  16. Input: grid = [[1,0,0],[1,1,0],[1,1,1]]
  17. Output: 0


  18. Constraints:

  19. n == grid.length
  20. n == grid[i].length
  21. 1 <= n <= 200
  22. grid[i][j] is 0 or 1
复制代码

  1. class Solution:
  2.     def minSwaps(self, grid: List[List[int]]) -> int:
  3.         zeros = [0 for _ in grid]
  4.         result = 0
  5.         for i in range(len(grid)):
  6.             count = 0
  7.             for j in range(len(grid[i]) - 1, -1, -1):
  8.                 if grid[i][j] != 0:
  9.                     break
  10.                 count += 1
  11.             zeros[i] = count
  12.         
  13.         n = len(grid)
  14.         for i in range(len(grid)):
  15.             target = n - i - 1
  16.             for j in range(i, len(grid) + 1):
  17.                
  18.                 if j < n and zeros[j] >= target:
  19.                     break
  20.             if j == n:
  21.                 return -1
  22.             result += j - i
  23.             temp = zeros[j]
  24.             for k in range(j, i, -1):
  25.                 zeros[k] = zeros[k - 1]
  26.             zeros[i] = temp
  27.         return result
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-23 16:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表