LeetCode 题解工作台

判断矩阵是否是一个 X 矩阵

如果一个正方形矩阵满足下述 全部 条件,则称之为一个 X 矩阵 : 矩阵对角线上的所有元素都 不是 0 矩阵中所有其他元素都是 0 给你一个大小为 n x n 的二维整数数组 grid ,表示一个正方形矩阵。如果 grid 是一个 X 矩阵 ,返回 true ;否则,返回 false 。 示例 1:…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们可以直接遍历矩阵,对于每个元素,判断其是否满足 矩阵的条件。若不满足,直接返回 ;若遍历完所有元素都满足,返回 。 时间复杂度 ,其中 为矩阵的行数或列数。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

如果一个正方形矩阵满足下述 全部 条件,则称之为一个 X 矩阵

  1. 矩阵对角线上的所有元素都 不是 0
  2. 矩阵中所有其他元素都是 0

给你一个大小为 n x n 的二维整数数组 grid ,表示一个正方形矩阵。如果 grid 是一个 X 矩阵 ,返回 true ;否则,返回 false

 

示例 1:

输入:grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
输出:true
解释:矩阵如上图所示。
X 矩阵应该满足:绿色元素(对角线上)都不是 0 ,红色元素都是 0 。
因此,grid 是一个 X 矩阵。

示例 2:

输入:grid = [[5,7,0],[0,3,1],[0,5,0]]
输出:false
解释:矩阵如上图所示。
X 矩阵应该满足:绿色元素(对角线上)都不是 0 ,红色元素都是 0 。
因此,grid 不是一个 X 矩阵。

 

提示:

  • n == grid.length == grid[i].length
  • 3 <= n <= 100
  • 0 <= grid[i][j] <= 105
lightbulb

解题思路

方法一:模拟

我们可以直接遍历矩阵,对于每个元素,判断其是否满足 XX 矩阵的条件。若不满足,直接返回 false\textit{false};若遍历完所有元素都满足,返回 true\textit{true}

时间复杂度 O(n2)O(n^2),其中 nn 为矩阵的行数或列数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def checkXMatrix(self, grid: List[List[int]]) -> bool:
        for i, row in enumerate(grid):
            for j, v in enumerate(row):
                if i == j or i + j == len(grid) - 1:
                    if v == 0:
                        return False
                elif v:
                    return False
        return True
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates understanding of matrix traversal and diagonal checking.

  • question_mark

    Look for an efficient solution that iterates through the matrix once, checking both conditions.

  • question_mark

    Candidate should handle edge cases, such as matrices where all elements are zero or matrices that are clearly non-X-Matrices.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the diagonal pattern or incorrectly checking non-diagonal elements.

  • error

    Over-complicating the solution by requiring additional space when O(1) space is sufficient.

  • error

    Not accounting for all matrix elements in the check, leading to incorrect results.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Adjust the problem to consider non-square matrices or non-integer elements.

  • arrow_right_alt

    Implement additional constraints like handling large grids efficiently.

  • arrow_right_alt

    Consider edge cases where the matrix has the minimum size (3x3) or elements are at their maximum values.

help

常见问题

外企场景

判断矩阵是否是一个 X 矩阵题解:数组·matrix | LeetCode #2319 简单