LeetCode 2319. Check if Matrix Is X-Matrix Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2319. Check if Matrix Is X-Matrix

Description

A square matrix is said to be an X-Matrix if both of the following conditions hold:

  1. All the elements in the diagonals of the matrix are non-zero.
  2. 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

Solutions

Solution 1: Simulation

We can directly traverse the matrix and check if each element satisfies the conditions of an X matrix. If any element does not satisfy the conditions, return false immediately. If all elements satisfy the conditions after traversal, return true.

The time complexity is O(n2), where n is the number of rows or columns of the matrix. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#C
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 True(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !