Saturday, June 3, 2017

Flipping the Matrix

Sean invented a game involving a  matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times, and the goal of the game is to maximize the sum of the elements in the  submatrix located in the upper-left corner of the  matrix (i.e., its upper-left quadrant).
Given the initial configurations for  matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal. For each matrix, print the maximized sum on a new line.
Input Format
The first line contains an integer, , denoting the number of queries. The subsequent lines describe each of the  queries in the following format:
  1. The first line of each query contains an integer, .
  2. Each line  the  subsequent lines contains  space-separated integers describing the respective values of row  in the matrix.
Output Format
You must print  lines of output. For each query (i.e., matrix), print the maximum possible sum of the elements in the matrix's upper-left quadrant.
Sample Input
1
2
112 42 83 119
56 125 56 49
15 78 101 43
62 98 114 108
Sample Output
414
Explanation
We start out with the following  matrix:
We can perform the following operations to maximize the sum of the  submatrix in the upper-left corner:
  1. Reverse column  (), resulting in the matrix: 
  2. Reverse row  (), resulting in the matrix: 
When we sum the values in the  submatrix in the upper-left quadrant, we get . Thus, we print  on a new line.
Solution:

for _ in range(int(input())):
    n = int(input()) 
    n2 = 2 * n
    maxSum = 0
    
    matrix = [0] * n2
    
    for i in range(n2):
        matrix[i] = [int(x) for x in input().strip().split()]
    for i in range(n):
        for j in range(n):
            maxSum += max([matrix[i][j],matrix[i][n2-1-j], matrix[n2-1-i][j],matrix[n2-1-i][n2-1-j]])
                   
    print (maxSum)
Share: