[LeetCode] Check if Matrix Is X-Matrix

2319. Check if Matrix Is X-Matrix

A square matrix is said to be an X-Matrix if both of the following conditions hold:

  1. All the elements in the diagonals of the matrix are non-zero.
  2. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool checkXMatrix(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for(int i = 0, l = 0, r = m - 1; i < n; i++,l++,r--) {
if(grid[i][l] == 0) return false;
if(grid[i][r] == 0) return false;
grid[i][l] = grid[i][r] = -1;
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == -1) continue;
if(grid[i][j]) return false;
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/26/PS/LeetCode/check-if-matrix-is-x-matrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.