Check if Matrix Is X-Matrix Problem
#2319
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2319.
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
Solution
Approach: Simulation
Check every cell. A cell on either diagonal (i == j or i + j == n - 1) must be non-zero, and every other cell must be zero. Return false on the first violation.
Complexity: Time O(n^2), space O(1).
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