判断矩阵是否是一个 X 矩阵【LC2319】
A square matrix is said to be an X-Matrix if both of the following conditions hold:
1.All the elements in the diagonals of the matrix are non-zero.
2.All other elements are 0.
Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.
感谢力扣 最近的都好简单 家里太忙了 没空学习了
- 思路:如果对角线的元素等于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 ( n 2 ) ,n 为矩阵的长度
- 空间复杂度:O ( 1 )