Check if Matrix Is X-Matrix

Here’s a solution which checks the X-Matrix conditions by iterating through the grid. It uses nested for loops to check each cell in the grid.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def checkXMatrix(self, grid: List[List[int]]) -> bool:
        n = len(grid)
        for i in range(n):
            for j in range(n):
                if i != j and i != n - j - 1:  # Not on either of the two diagonals
                    if grid[i][j] != 0:
                        return False  # All other elements must be 0
                else:  # On either of the two diagonals
                    if grid[i][j] == 0:
                        return False  # All elements in the diagonals must be non-zero
        return True  # Passed all checks

This code first checks if the current cell (grid[i][j]) is not on either of the two diagonals. If it’s not, the value in this cell must be 0. If it’s not 0, we return False immediately because this violates the X-Matrix condition.

Then, if the current cell is on either of the two diagonals, the value in this cell must not be 0. If it is 0, we return False immediately because this also violates the X-Matrix condition.

Finally, if the code doesn’t return False after checking every cell in the grid, that means the grid passes all checks and it’s an X-Matrix. So we return True.