Input: grid =[[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]Output: trueExplanation: 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.
Input: grid =[[5,7,0],[0,3,1],[0,5,0]]Output: falseExplanation: 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.
For a matrix to be an X-Matrix, all diagonal elements (main and anti-diagonal) must be non-zero, and all other elements must be zero. We can check each cell and verify these conditions directly.
classSolution {
public:bool checkXMatrix(vector<vector<int>>& grid) {
int n = grid.size();
for (int i =0; i < n; ++i) {
for (int j =0; j < n; ++j) {
if (i == j || i + j == n -1) {
if (grid[i][j] ==0) return false;
} else {
if (grid[i][j] !=0) return false;
}
}
}
return true;
}
};
classSolution {
publicbooleancheckXMatrix(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) {
if (grid[i][j]== 0) returnfalse;
} else {
if (grid[i][j]!= 0) returnfalse;
}
}
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funcheckXMatrix(grid: Array<IntArray>): Boolean {
val n = grid.size
for (i in0 until n) {
for (j in0 until n) {
if (i == j || i + j == n - 1) {
if (grid[i][j] ==0) returnfalse } else {
if (grid[i][j] !=0) returnfalse }
}
}
returntrue }
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defcheckXMatrix(self, grid: list[list[int]]) -> bool:
n = len(grid)
for i in range(n):
for j in range(n):
if i == j or i + j == n -1:
if grid[i][j] ==0:
returnFalseelse:
if grid[i][j] !=0:
returnFalsereturnTrue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfncheck_x_matrix(grid: Vec<Vec<i32>>) -> bool {
let n = grid.len();
for i in0..n {
for j in0..n {
if i == j || i + j == n -1 {
if grid[i][j] ==0 {
returnfalse;
}
} else {
if grid[i][j] !=0 {
returnfalse;
}
}
}
}
true }
}