Skip to content

2319. Check if Matrix Is X-Matrix 👍

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool checkXMatrix(vector<vector<int>>& grid) {
    const int n = grid.size();

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        if (i == j || i + j == n - 1) {  // in diagonal
          if (grid[i][j] == 0)
            return false;
        } else if (grid[i][j]) {  // not in diagonal
          return false;
        }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean checkXMatrix(int[][] grid) {
    final int n = grid.length;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        if (i == j || i + j == n - 1) { // in diagonal
          if (grid[i][j] == 0)
            return false;
        } else if (grid[i][j] > 0) { // not in diagonal
          return false;
        }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def checkXMatrix(self, grid: list[list[int]]) -> bool:
    n = len(grid)

    for i in range(n):
      for j in range(n):
        if i == j or i + j == n - 1:  # in diagonal
          if grid[i][j] == 0:
            return False
        elif grid[i][j]:   # not in diagonal
          return False

    return True