Leetcode 2319. Check if Matrix Is X
Given a square matrix grid
, return true
if the matrix is an X-Matrix. Otherwise, return false
.
An X-Matrix has the following properties:
For example:
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],
[1,0,5]]
Output: false
To determine if a given matrix is an X-Matrix, use the following steps:
i == j
i + j == n - 1
true
if both conditions are satisfied for all elements, otherwise return false
.#include <vector>
using namespace std;
class Solution {
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;
}
};
The time complexity of this solution is (O(n^2)) because we need to iterate through each element in the n x n
matrix exactly once to check the conditions.
i == j
are points on the primary diagonal.i + j == n - 1
are points on the secondary diagonal.i == j
or i + j == n - 1
), ensure they are non-zero.This approach ensures that every element is checked exactly once, leading to optimal performance.
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?