File: check-if-matrix-is-x-matrix/solution.py

Date: 2026-06-06

Time: 15:39

Purpose

This file solves LeetCode 2319: Check if Matrix Is X-Matrix. An X-Matrix is a square matrix where every element on both diagonals is non-zero and every element *not* on a diagonal is zero. The file's sole responsibility is implementing and exposing that check.

Key Components

Solution.checkXMatrix(grid) -> bool

The main logic. Takes an n x n grid and returns whether it satisfies the X-Matrix property. The contract is simple: the grid must be square (guaranteed by the problem), and the method performs a single pass over all cells.

checkifmatrixisx_matrix (module-level lambda)

A thin wrapper that instantiates Solution and delegates. This exists to match the project's naming convention — test files import a snake_case function named after the problem directory.

Patterns

Dependencies

Imports: None — pure stdlib types (list[int]).

Imported by: check-if-matrix-is-x-matrix/test_solution.py directly. The "Imported By" list in the prompt is misleading — those hundreds of test files each import their *own* solution module, not this one. Only this problem's test file imports this file.

Flow

1. Read n from len(grid).

2. For each cell (i, j):

3. If no cell violated, return True.

The two diagonal conditions share the center cell when n is odd (where i == j == n // 2 and i + j == n - 1 are both true). This is fine — it's checked once and the non-zero constraint applies either way.

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. An empty grid (n == 0) would skip the loops and return True, which is arguably correct (vacuously an X-Matrix).

Topics to Explore

Beliefs