Skip to content

Commit ba317d0

Browse files
authored
Create minimum-swaps-to-arrange-a-binary-grid.py
1 parent 9aaf036 commit ba317d0

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time: O(n^2)
2+
# Space: O(1)
3+
4+
import itertools
5+
6+
7+
class Solution(object):
8+
def minSwaps(self, grid):
9+
"""
10+
:type grid: List[List[int]]
11+
:rtype: int
12+
"""
13+
result = 0
14+
for target in reversed(xrange(1, len(grid))):
15+
row_idx = len(grid)-1-target
16+
while row_idx < len(grid):
17+
row = grid[row_idx]
18+
if not sum(itertools.islice(row, len(row)-target, len(row))):
19+
break
20+
row_idx += 1
21+
else:
22+
return -1
23+
while row_idx != len(grid)-1-target:
24+
grid[row_idx], grid[row_idx-1] = grid[row_idx-1], grid[row_idx]
25+
result += 1
26+
row_idx -= 1
27+
return result

0 commit comments

Comments
 (0)