Check if Matrix Is X-Matrix

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
2 0 0 1
0 3 1 0
0 5 2 0
4 0 0 2
Inputgrid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Outputtrue
The diagonal elements are non-zero and all other elements are 0, so grid is an X-Matrix.
Example 2
5 7 0
0 3 1
0 5 0
Inputgrid = [[5,7,0],[0,3,1],[0,5,0]]
Outputfalse
The matrix does not satisfy the X-Matrix conditions, so grid is not an X-Matrix.

Constraints

  • n == grid.length == grid[i].length
  • 3 <= n <= 100
  • 0 <= grid[i][j] <= 10^5

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate