2319. 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.
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; } };
|