Check if Matrix Is X-Matrix — LeetCode 2319 Python Solution
- Problem
- #2319
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i, row in enumerate(grid):
for j, v in enumerate(row):
if i == j or i + j == len(grid) - 1:
if v == 0:
return False
elif v:
return False
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the number of rows or columns of the matrix |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2319. Check if Matrix Is X-Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2319. Check if Matrix Is X-Matrix?
- LeetCode 2319. Check if Matrix Is X-Matrix is rated Easy on LeetCode.
- What topics does LeetCode 2319. Check if Matrix Is X-Matrix cover?
- LeetCode 2319. Check if Matrix Is X-Matrix is tagged Array and Matrix on LeetCode.