判断矩阵是否是一个 X 矩阵【LC2319】
A square matrix is said to be an X-Matrix if both of the following conditions hold:
- All the elements in the diagonals of the matrix are non-zero.
- All other elements are 0.
Given a 2D integer array
grid
of sizen x n
representing a square matrix, returntrue
ifgrid
is an X-Matrix. Otherwise, returnfalse
.
感谢力扣 最近的都好简单 家里太忙了 没空学习了
-
思路:如果对角线的元素等于0或者其他元素不等于0,那么返回false
-
实现
class Solution { public boolean checkXMatrix(int[][] grid) { 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){ if (grid[i][j] == 0) return false; }else{ if (grid[i][j] != 0) return false; } } } return true; } }
- 复杂度
- 时间复杂度:O(n2)O(n^2)O(n2),nnn为矩阵的长度
- 空间复杂度:O(1)O(1)O(1)
- 复杂度