2319. Check if Matrix Is X Matrix

2319. Check if Matrix Is X-Matrix #

题目 #

  • X 矩阵 是满足下列条件的方阵
    • 矩阵对角线上所有元素都 非零
    • 非对角线元素均 为零
  • 给定 n 阶方阵 grid,判断 grid 是否为 X 矩阵

思路 #

模拟 #

代码 #

模拟 #

class Solution {
    public boolean checkXMatrix(int[][] grid) {
        boolean valid = true;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid.length; j++) {
                if (i == j) valid &= grid[i][j] != 0;
                else if (j == grid.length - 1 - i) valid &= grid[i][j] != 0;
                else valid &= grid[i][j] == 0;
            }
        }
        return valid;
    }
}