Python3程序通过旋转所有行或所有列来最大化矩阵的对角线之和
给定一个维度为N * N的方阵mat[][] ,任务是通过将矩阵的所有行或所有列旋转一个正整数来从给定矩阵中找到可能的对角线元素的最大总和。
例子:
Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }
Output: 6
Explanation:
Rotating all the columns of matrix by 1 modifies mat[][] to { {2, 1, 2}, {1, 2, 2}, {1, 1, 2} }.
Therefore, the sum of diagonal elements of the matrix = 2 + 2 + 2 = 6 which is the maximum possible.
Input: A[][] = { { -1, 2 }, { -1, 3 } }
Output: 2
方法:想法是用所有可能的方式旋转矩阵的所有行和列,并计算得到的最大和。请按照以下步骤解决问题:
- 初始化一个变量,比如maxDiagonalSum ,通过旋转矩阵的所有行或列来存储矩阵的对角元素的最大可能总和。
- 将矩阵的所有行旋转[0, N – 1]范围内的正整数并更新maxDiagonalSum的值。
- 将矩阵的所有列旋转[0, N – 1]范围内的正整数并更新maxDiagonalSum的值。
- 最后,打印maxDiagonalSum的值。
下面是上述方法的实现:
Python3
# Python3 program to implement
# the above approach
import sys
N = 3
# Function to find maximum sum of diagonal
# elements of matrix by rotating either
# rows or columns
def findMaximumDiagonalSumOMatrixf(A):
# Stores maximum diagonal sum of elements
# of matrix by rotating rows or columns
maxDiagonalSum = -sys.maxsize - 1
# Rotate all the columns by an integer
# in the range [0, N - 1]
for i in range(N):
# Stores sum of diagonal elements
# of the matrix
curr = 0
# Calculate sum of diagonal
# elements of the matrix
for j in range(N):
# Update curr
curr += A[j][(i + j) % N]
# Update maxDiagonalSum
maxDiagonalSum = max(maxDiagonalSum,
curr)
# Rotate all the rows by an integer
# in the range [0, N - 1]
for i in range(N):
# Stores sum of diagonal elements
# of the matrix
curr = 0
# Calculate sum of diagonal
# elements of the matrix
for j in range(N):
# Update curr
curr += A[(i + j) % N][j]
# Update maxDiagonalSum
maxDiagonalSum = max(maxDiagonalSum,
curr)
return maxDiagonalSum
# Driver code
if __name__ == "__main__":
mat = [ [ 1, 1, 2 ],
[ 2, 1, 2 ],
[ 1, 2, 2 ] ]
print(findMaximumDiagonalSumOMatrixf(mat))
# This code is contributed by chitranayal
输出:
6
时间复杂度: O(N 2 )
辅助空间: O(1)
有关详细信息,请参阅有关通过旋转所有行或所有列来最大化矩阵的对角线总和的完整文章!