forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-all-ones-with-row-and-column-flips-ii.py
45 lines (41 loc) · 1.35 KB
/
remove-all-ones-with-row-and-column-flips-ii.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Time: O(m * n * 2^(m * n))
# Space: O(2^(m * n))
# dp, bitmasks
class Solution(object):
def removeOnes(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
rows = [0]*len(grid)
mask, bit = 0, 1
for _ in xrange(len(grid[0])):
mask += bit
bit <<= 1
for i in xrange(len(grid)):
rows[i] = mask
mask <<= len(grid[0])
cols = [0]*len(grid[0])
mask, bit = 0, 1
for _ in xrange(len(grid)):
mask += bit
bit <<= len(grid[0])
for j in xrange(len(grid[0])):
cols[j] = mask
mask <<= 1
full_mask = (1<<(len(grid)*len(grid[0])))-1
masks = [[full_mask for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))]
target, bit = 0, 1
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
target += bit*grid[i][j]
masks[i][j] -= (rows[i]+cols[j]-bit)
bit <<= 1
dp = [float("inf") for _ in xrange(target+1)]
dp[0] = 0
for mask in xrange(1, target+1):
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j]:
dp[mask] = min(dp[mask], dp[mask&masks[i][j]]+1)
return dp[target]