Maximum sum of k connected elements of a matrix

前端 未结 1 692
無奈伤痛
無奈伤痛 2020-12-30 11:38

Given a grid with positive integer values and an integer K. What is the maximum sum of K connected elements ?

Here is a example of

相关标签:
1条回答
  • 2020-12-30 12:10

    I suppose you could meander around, memoizing as you go. I used mirror-image bitsets to represent the memoized paths so that they would be instantly recognizable from any direction they get constructed. Here's a version in Python (the hash length includes counts for paths from sizes one to six):

    from sets import Set
    
    def f(a,k):
      stack = []
      hash = Set([])
      best = (0,0) # sum, path
      n = len(a)
    
      for y in range(n):
        for x in range(n):
          stack.append((1 << (n * y + x),y,x,a[y][x],1))
    
      while len(stack) > 0:
        (path,y,x,s,l) = stack.pop()
    
        if l == k and path not in hash:
          hash.add(path)
          if s > best[0]:
            best = (s,path)
        elif path not in hash:
          hash.add(path)
          if y < n - 1:
            stack.append((path | (1 << (n * (y + 1) + x)),y + 1,x,s + a[y + 1][x],l + 1))
          if y > 0:
            stack.append((path | (1 << (n * (y - 1) + x)),y - 1,x,s + a[y - 1][x],l + 1))
          if x < n - 1:
            stack.append((path | (1 << (n * y + x + 1)),y,x + 1,s + a[y][x + 1],l + 1))
          if x > 0:
            stack.append((path | (1 << (n * y + x - 1)),y,x - 1,s + a[y][x - 1],l + 1))
    
      print best
      print len(hash)
    

    Output:

    arr = [[31,12,7,1,14]
          ,[23,98,3,87,1]
          ,[5,31,8,2,99]
          ,[12,3,42,17,88]
          ,[120,2,7,5,7]]
    
    f(arr,6) 
    
    """ 
    (377, 549312) sum, path
    1042 hash length
    549312 = 00000
             01110
             11000
             10000 
    """
    

    UPDATE: This question is similar to this one, Whats the fastest way to find biggest sum of M adjacent elements in a matrix, and I realized that a revision is needed in my suggestion to include formations extending from middle sections of the shapes. Here's my revised code, using sets to hash the shapes. It seems to me that a DFS ought to keep the stack size on the order of O(m) (although the search space is still huge).

    from sets import Set
    
    def f(a,m):
      stack = []
      hash = Set([])
      best = (0,[]) # sum, shape
      n = len(a)
    
      for y in range(n):
        for x in range(n):
          stack.append((a[y][x],Set([(y,x)]),1))
    
      while len(stack) > 0:
        s,shape,l = stack.pop()
    
        key = str(sorted(list(shape)))
    
        if l == m and key not in hash:
          hash.add(key)
          if s > best[0]:
            best = (s,shape)
        elif key not in hash:
          hash.add(key)
          for (y,x) in shape:
            if y < n - 1 and (y + 1,x) not in shape:
              copy = Set(shape)
              copy.add((y + 1,x))
              stack.append((s + a[y + 1][x],copy,l + 1))
            if y > 0 and (y - 1,x) not in shape:
              copy = Set(shape)
              copy.add((y - 1,x))
              stack.append((s + a[y - 1][x],copy,l + 1))
            if x < n - 1 and (y,x + 1) not in shape:
              copy = Set(shape)
              copy.add((y,x + 1))
              stack.append((s + a[y][x + 1],copy,l + 1))
            if x > 0 and (y,x - 1) not in shape:
              copy = Set(shape)
              copy.add((y,x - 1))
              stack.append((s + a[y][x - 1],copy,l + 1))
    
      print best
      print len(hash)
    

    Output:

    arr = [[31,12,7,1,14]
          ,[23,98,3,87,1]
          ,[5,31,8,2,99]
          ,[12,3,42,17,88]
          ,[120,2,7,5,7]]
    
    f(arr,6)
    
    """
    (377, Set([(1, 2), (1, 3), (1, 1), (2, 3), (3, 4), (2, 4)]))
    2394 hash length
    """
    
    0 讨论(0)
提交回复
热议问题