[Leetcode] 3122. Minimum Number of Operations to Satisfy Conditions (RETRY!! i dont get)

whitehousechef·2025년 6월 2일

https://leetcode.com/problems/find-closest-node-to-given-two-nodes/description/?envType=daily-question&envId=2025-05-30

initial

much harder than https://velog.io/@whitehousechef/Leetcode-135.-Candy

I thought we can just do greedily with 2 pass but actually if we have

1 2
2 1
2 2

if we convert first col to 2, we cant make the second col change to 2 as well

my initial approach greedy

class Solution:
    def minimumOperations(self, grid: List[List[int]]) -> int:
        row,col=len(grid),len(grid[0])
        dp=[2000 for _ in range(col)]
        prevCol=1001
        realPrevCol=-1
        ans=0
        for i in range(col):
            for j in range(10):
                if j==realPrevCol:
                    continue
                check = 0
                for k in range(row):
                    if grid[k][i]!=j:
                        check+=1
                if dp[i]>check:
                    dp[i]=check
                    prevCol=j
            realPrevCol = prevCol
            print(realPrevCol)
        return sum(dp)

sol

instead of using 1d dp, we have to use 2d dp where
dp[i][j] is min. number of operations to fill from column 0 to column j with value i.

We also have to check if current col has a different value than previous col

i dont get it

0개의 댓글