Bomb dropping algorithm

后端 未结 30 833
挽巷
挽巷 2021-01-29 16:55

I have an n x m matrix consisting of non-negative integers. For example:

2 3 4 7 1
1 5 2 6 2
4 3 4 2 1
2 1 2 4 1
3 1 3 4 1
2 1 4 3 2
6 9 1 6 4
         


        
30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-29 17:50

    All this problem boils down to is computing an edit distance. Simply calculate a variant of the Levenshtein distance between the given matrix and the zero matrix, where edits are replaced with bombings, using dynamic programming to store the distances between intermediate arrays. I suggest using a hash of the matrices as a key. In pseudo-Python:

    memo = {}
    
    def bomb(matrix,i,j):
        # bomb matrix at i,j
    
    def bombsRequired(matrix,i,j):
        # bombs required to zero matrix[i,j]
    
    def distance(m1, i, len1, m2, j, len2):
        key = hash(m1)
        if memo[key] != None: 
            return memo[key]
    
        if len1 == 0: return len2
        if len2 == 0: return len1
    
        cost = 0
        if m1 != m2: cost = m1[i,j]
        m = bomb(m1,i,j)
        dist = distance(str1,i+1,len1-1,str2,j+1,len2-1)+cost)
        memo[key] = dist
        return dist
    

提交回复
热议问题