LeetCode Weekly Contest No. 299 (1/4)

该博客介绍了一个编程问题,目标是检查一个给定的二维整数矩阵是否符合X-Matrix的定义,即对角线上的元素非零,其余元素为零。通过遍历矩阵并检查对角线元素和非对角线元素来实现这一判断。提供的解决方案使用Python代码实现了这一逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

  1. All the elements in the diagonals of the matrix are non-zero.
  2. 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].length
  • 3 <= n <= 100
  • 0 <= 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值