Similar Problems

Similar Problems not available

Check If Matrix Is X Matrix - Leetcode Solution

Companies:

LeetCode:  Check If Matrix Is X Matrix Leetcode Solution

Difficulty: Easy

Topics: matrix array  

Problem Statement:

Given a square matrix mat of size N x N. Write a function to determine if it is an X-matrix or not. An X-matrix can be shown as below:

x . . . . . x . . . . . x . . . . . x .

Examples:

Input: [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]] Output: True

Input: [[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,0,1]] Output: False

Solution:

The solution to this problem is very simple. We can just go through the matrix and check if all the elements on the main diagonal are equal to each other, and all the elements on the reverse diagonal are equal to each other. If these conditions are met, then we can say that the matrix is an X matrix.

To check the main diagonal and reverse diagonal, we can use two loops. The first loop will iterate through the rows, and the second loop will iterate through the columns. To check the main diagonal, we can check if the row and column index are equal. To check the reverse diagonal, we can check if the sum of the row and column index is equal to n-1.

Pseudo code:

  1. Create a variable bool isX = true
  2. For row i = 0 to N-1 do the following: a. If mat[i][i] != mat[0][0], set isX to false and break b. If mat[i][N-1-i] != mat[0][N-1], set isX to false and break
  3. Return isX

The time complexity of this approach is O(N), where N is the size of the matrix.

Code:

bool isXMatrix(vector<vector<int>>& mat) { int n = mat.size(); bool isX = true;

// check main diagonal and reverse diagonal
for(int i=0; i<n; i++) {
    if(mat[i][i] != mat[0][0] || mat[i][n-1-i] != mat[0][n-1]) {
        isX = false;
        break;
    }
}

return isX;

}

Check If Matrix Is X Matrix Solution Code

1