i == j
).i + j == n - 1
).False
.True
.def checkXMatrix(grid):
n = len(grid) # The matrix is n x n
for i in range(n):
for j in range(n):
if i == j or i + j == n - 1:
# Primary diagonal or secondary diagonal element
if grid[i][j] == 0:
return False
else:
# Non-diagonal element
if grid[i][j] != 0:
return False
return True
n
is the size of the grid (number of rows/columns). This is because we need to check each element in the n x n matrix exactly once.# Sample test case
matrix = [
[2, 0, 0, 1],
[0, 3, 1, 0],
[0, 5, 2, 0],
[4, 0, 0, 2]
]
print(checkXMatrix(matrix)) # Output should be True as it is an X-Matrix
matrix = [
[2, 0, 4, 1],
[0, 3, 0, 0],
[0, 0, 2, 0],
[4, 0, 0, 2]
]
print(checkXMatrix(matrix)) # Output should be False as it is not an X-Matrix
This logic should help you implement the solution to check if a given matrix is an X-Matrix. If you have any further questions or need additional test cases, feel free to ask!
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?