Skip to content

Commit e39e19a

Browse files
committed
Add LeetCode solution 1536
1 parent ff5c4c1 commit e39e19a

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#!/usr/bin/env python3
2+
3+
"""LeetCode solution 01536."""
4+
5+
import unittest
6+
7+
8+
class Solution(object):
9+
def minSwaps(self, grid):
10+
"""
11+
:type grid: List[List[int]]
12+
:rtype: int
13+
"""
14+
n = len(grid)
15+
trailing_zeros = [0] * n
16+
17+
for i in range(n):
18+
tail_zeros = 0
19+
for j in range(n - 1, -1, -1):
20+
if grid[i][j]:
21+
break
22+
tail_zeros += 1
23+
24+
trailing_zeros[i] = tail_zeros
25+
26+
answer = 0
27+
for i in range(n - 1):
28+
required = n - i - 1
29+
30+
index = -1
31+
for j in range(i, n):
32+
if trailing_zeros[j] >= required:
33+
index = j
34+
break
35+
36+
if index == -1:
37+
return -1
38+
39+
while index > i:
40+
answer += 1
41+
trailing_zeros[index - 1], trailing_zeros[index] = (
42+
trailing_zeros[index],
43+
trailing_zeros[index - 1],
44+
)
45+
index -= 1
46+
47+
return answer
48+
49+
50+
class TestSolution(unittest.TestCase):
51+
def test_minSwaps(self):
52+
solution = Solution()
53+
self.assertEqual(solution.minSwaps([[0, 0, 1], [1, 1, 0], [1, 0, 0]]), 3)
54+
55+
56+
if __name__ == '__main__':
57+
unittest.main()

0 commit comments

Comments
 (0)