Leetcode 2319: Check if Matrix Is X-Matrix

grid47
grid47
Exploring patterns and algorithms
Mar 20, 2024 5 min read

A matrix is called an X-Matrix if all elements along the diagonals are non-zero, and all elements outside the diagonals are zero. Given a 2D integer array grid representing a matrix, return true if it is an X-Matrix, otherwise return false.
Problem
Approach
Steps
Complexity
Input: The input consists of an n x n matrix grid, where n is the number of rows and columns. The elements in the grid are integers.
Example: grid = [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
Constraints:
• 3 <= n <= 100
• 0 <= grid[i][j] <= 10^5
Output: Return true if the grid is an X-Matrix, otherwise return false.
Example: For grid = [[1, 0, 0], [0, 2, 0], [0, 0, 3]], the output is true.
Constraints:
• The result should be a boolean value.
Goal: To determine if the matrix is an X-Matrix by checking if all diagonal elements are non-zero and all non-diagonal elements are zero.
Steps:
• 1. Iterate through the matrix elements.
• 2. For each element at position (i, j):
• a. If the element is on a diagonal (i == j or i + j == n - 1), check if it is non-zero.
• b. If the element is not on a diagonal, check if it is zero.
• 3. If any condition fails, return false. If all conditions hold, return true.
Goal: The matrix size must be at least 3x3 and at most 100x100. The elements must be integers within the range 0 to 10^5.
Steps:
• 3 <= n <= 100
• 0 <= grid[i][j] <= 10^5
Assumptions:
• The matrix is always square (n x n).
Input: grid = [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
Explanation: In this case, the matrix is an X-Matrix because the diagonal elements (1, 2, 3) are non-zero, and all other elements are zero.

Input: grid = [[1, 0, 0], [0, 0, 0], [0, 0, 3]]
Explanation: Here, the matrix is not an X-Matrix because the diagonal element at position (1,1) is 0, while it should be non-zero.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus