Skip to content

Commit 0590ad5

Browse files
committed
190125
1 parent 5eff2de commit 0590ad5

File tree

2 files changed

+65
-2
lines changed

2 files changed

+65
-2
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from typing import List
2+
3+
4+
# leetcode submit region begin(Prohibit modification and deletion)
5+
class Solution:
6+
def minCost(self, grid: List[List[int]]) -> int:
7+
DIRECTIONS = {
8+
1: (0, 1),
9+
2: (0, -1),
10+
3: (1, 0),
11+
4: (-1, 0),
12+
}
13+
14+
N = len(grid)
15+
M = len(grid[0])
16+
17+
def is_valid_idx(i, j):
18+
return i >= 0 and i < N and j >= 0 and j < M
19+
20+
def go(i, j, total_cost, flipped):
21+
if total_cost < 0:
22+
return False
23+
if i == N - 1 and j == M - 1:
24+
return True
25+
26+
next_direction = grid[i][j]
27+
28+
for d in range(1, 5):
29+
cost = 1 if d != next_direction else 0
30+
next_i, next_j = i + DIRECTIONS[d][0], j + DIRECTIONS[d][1]
31+
if not is_valid_idx(next_i, next_j):
32+
continue
33+
if cost == 1:
34+
flipped[i][j] += cost
35+
if flipped[i][j] < 2:
36+
if go(next_i, next_j, (total_cost - cost), flipped):
37+
return True
38+
flipped[i][j] -= cost
39+
return False
40+
41+
def good(total_cost_allowed):
42+
return go(0, 0, total_cost_allowed, [[0 for _ in range(M)] for _ in range(N)])
43+
44+
left = 0
45+
right = N * M + 1
46+
ans = 10 ** 20
47+
while left < right:
48+
mid = (left + right) // 2
49+
if good(mid):
50+
ans = mid
51+
right = mid
52+
else:
53+
left = mid + 1
54+
return ans
55+
56+
57+
# leetcode submit region end(Prohibit modification and deletion)
58+
59+
60+
class MinimumCostToMakeAtLeastOneValidPathInAGrid(Solution):
61+
pass

main.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from leetcode.editor.en.Q2683.NeighboringBitwiseXor import NeighboringBitwiseXor
1+
from leetcode.editor.en.Q1368.MinimumCostToMakeAtLeastOneValidPathInAGrid import \
2+
MinimumCostToMakeAtLeastOneValidPathInAGrid
23

34
if __name__ == '__main__':
4-
print(NeighboringBitwiseXor().doesValidArrayExist(derived=[1, 0]))
5+
print(
6+
MinimumCostToMakeAtLeastOneValidPathInAGrid().minCost([[1, 1, 1, 1], [2, 2, 2, 2], [1, 1, 1, 1], [2, 2, 2, 2]]))

0 commit comments

Comments
 (0)