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.
|
|
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.