Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum sum of k connected elements of a matrix

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 a 5x5 matrix with a K value of 6.

Example

Someone can help me to identify this problem? how can i start to solve it ?
The only way i know is to do a depth first search for each cell of this matrix. But i think that this is not the best approach.

Repeating cells are not allowed.

Connected here means only that a cell is adjacent to the other horizontally or vertically

like image 648
Felipe Avatar asked Sep 28 '15 13:09

Felipe


People also ask

How do you find the maximum sum of a matrix?

To find max path sum first we have to find max value in first row of matrix. Store this value in res. Now for every element in matrix update element with max value which can be included in max path. If the value is greater then res then update res.

What is the sum of all elements of a matrix?

To find the sum of all the elements of a matrix, you can use the sum() function. In the case of a matrix, you have to use the sum() function two times, one for rows and one for columns, but in the case of a vector, you have to use the sum() only one time.


1 Answers

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
"""
like image 177
גלעד ברקן Avatar answered Nov 15 '22 07:11

גלעד ברקן