Problem 1. 2319. Check if Matrix Is X-Matrix
题目描述:
A square matrix is said to be an X-Matrix if both of the following conditions hold:
- All the elements in the diagonals of the matrix are non-zero.
- All other elements are 0.
Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.
Example 1:

Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]] Output: true Explanation: Refer to the diagram above. An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0. Thus, grid is an X-Matrix.
Example 2:

Input: grid = [[5,7,0],[0,3,1],[0,5,0]] Output: false Explanation: Refer to the diagram above. An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0. Thus, grid is not an X-Matrix.
Constraints:
n == grid.length == grid[i].length3 <= n <= 1000 <= grid[i][j] <= 10^5
解题思路:
这个题要判断一个矩阵是否满足下面两个条件:
1. 对角线上全不为0
2. 非对角线上全为0
我们只需要搞清楚对角线的特征。
假设(i,j)是第i行、第j列元素,则它在对角线上的充要条件为:
i+j==n-1 || i==j
搞清楚这一点,于是:
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
n = len(grid)
for i, j in itertools.product(range(n), range(n)):
if i == j or i + j == n - 1:
if grid[i][j] == 0: return False
else:
if grid[i][j] != 0: return False
return True
该博客介绍了一个编程问题,目标是检查一个给定的二维整数矩阵是否符合X-Matrix的定义,即对角线上的元素非零,其余元素为零。通过遍历矩阵并检查对角线元素和非对角线元素来实现这一判断。提供的解决方案使用Python代码实现了这一逻辑。
356

被折叠的 条评论
为什么被折叠?



