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
.
Example 1:
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]] Output: true Explanation: 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.
Example 2:
Input: grid = [[5,7,0],[0,3,1],[0,5,0]] Output: false Explanation: 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.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
0 <= grid[i][j] <= 105
Solution
Time Complexity: O(m + n)
Space Complexity: O(1)
class Solution {
public:
bool checkXMatrix(vector<vector<int>>& g) {
for (int i = 0; i < g.size(); ++i)
for (int j = 0; j < g[i].size(); ++j) {
if (i == j || i + j == g.size() - 1) {
if (g[i][j] == 0)
return false;
}
else if (g[i][j] > 0)
return false;
}
return true;
}
};
class Solution {
public boolean checkXMatrix(int[][] grid) {
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
if((i == j) || (i+j)==(grid.length-1))
{
if(grid[i][j] == 0)
return false;
}
else
{
if(grid[i][j] !=0)
return false;
}
}
}
return true;
}
}
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
globalSum, diagonalSum = 0, 0
for i in range(len(grid)):
for j in range(len(grid[0])):
globalSum += grid[i][j]
#principle diagonal
if grid[i][i] == 0 or grid[i][len(grid)-1-i] == 0:
return False
diagonalSum += grid[i][i] + grid[i][len(grid)-1-i]
if len(grid) % 2 != 0:
mid = len(grid) // 2
diagonalSum -= grid[mid][mid]
return True if diagonalSum == globalSum else False
Happy Learning – If you require any further information, feel free to contact me.