Leetcode 2319. Check if Matrix Is X
You are given a 2D integer array grid
of size n x n
representing a square matrix. An X-Matrix is a matrix where all the elements in the diagonals of the matrix are non-zero and all other elements are 0.
Given this definition, an element grid[i][j]
is part of the diagonals if either:
i == j
(it is on the primary diagonal),i + j == n - 1
(it is on the secondary diagonal).Return true
if grid
is an X-Matrix. Otherwise, return false
.
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Output: true
Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
Output: false
Explanation: One of the elements in the diagonals is zero.
1 <= n <= 100
.grid[i][j]
:
i == j
or i + j == n - 1
), it should be non-zero.public class Solution {
public boolean checkXMatrix(int[][] grid) {
int n = grid.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || i + j == n - 1) {
// Element is on the diagonal
if (grid[i][j] == 0) {
return false;
}
} else {
// Element is not on the diagonal
if (grid[i][j] != 0) {
return false;
}
}
}
}
return true;
}
}
This approach should efficiently determine if the matrix grid
is an X-Matrix based on the defined criteria.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?