#2319
Easy Algorithms Check if matrix is x matrix
Array Matrix
66.4% acceptance
Feb 25, 2026
546
26
A square matrix is said to be an X-Matrix if:
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, return true if grid is an X-Matrix. Otherwise, return false.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn check_x_matrix(grid: Vec<Vec<i32>>) -> bool {
let n = grid.len();
for i in 0..n {
for j in 0..n {
let on_diag = i == j || i + j == n - 1;
if on_diag {
if grid[i][j] == 0 {
return false;
}
} else if grid[i][j] != 0 {
return false;
}
}
}
true
}
}