Advertisement
Fhernd

matrix-land.py

Nov 11th, 2018
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. import sys
  2. from array import array
  3.  
  4. def matrixLand(grid):
  5.     width = len(grid[0])
  6.     prevline = array('l',[0]) * width
  7.    
  8.     for line in grid:
  9.         going_left = array('l',[0]) * width
  10.         going_right = array('l',[0]) * width
  11.        
  12.         top, notop = -2000000000, 0
  13.         for i in range(width):
  14.             notop = max(0,notop)
  15.             going_right[i] += notop
  16.             notop += line[i]
  17.             top = max(top+line[i], prevline[i]+notop)
  18.             going_left[i] += top
  19.  
  20.         top, notop = -2000000000, 0
  21.         for i in range(width-1,-1,-1):
  22.             notop = max(0,notop)
  23.             going_left[i] += notop
  24.             notop += line[i]
  25.             top = max(top+line[i], prevline[i]+notop)
  26.             going_right[i] += top
  27.            
  28.         for i in range(width):
  29.             prevline[i] = max(going_left[i], going_right[i])
  30.            
  31.     return max(prevline)
  32.  
  33.  
  34. n, m = [int(x) for x in input().split()]
  35.  
  36. if m == 1:
  37.     print(sum(int(x) for x in sys.stdin))
  38. else:    
  39.     grid = []
  40.     for _ in range(n):
  41.         grid.append(array('l',(int(x) for x in sys.stdin.readline().split(' '))))
  42.     result = matrixLand(grid)
  43.     print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement