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 size n x n
representing a square matrix, return true
if grid
is an X-Matrix. Otherwise, return false
.
Example 1:
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]] Output: true Explanation: Refer to the diagram above. An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0. Thus, grid is an X-Matrix.
Example 2:
Input: grid = [[5,7,0],[0,3,1],[0,5,0]] Output: false Explanation: Refer to the diagram above. An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0. Thus, grid is not an X-Matrix.
Constraints:
n == grid.length == grid[i].length
3 <= n <= 100
0 <= grid[i][j] <= 105
判断矩阵是否是一个 X 矩阵。
如果一个正方形矩阵满足下述 全部 条件,则称之为一个 X 矩阵 :
矩阵对角线上的所有元素都 不是 0
矩阵中所有其他元素都是 0
给你一个大小为 n x n 的二维整数数组 grid ,表示一个正方形矩阵。如果 grid 是一个 X 矩阵 ,返回 true ;否则,返回 false 。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/check-if-matrix-is-x-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道判断矩阵坐标的题,需要对矩阵的坐标比较敏感。如果矩阵的长度和宽度分别是 m 和 n 的,那么判断对角线的时候,有
- 左上 - 右下, i == j
- 右上 - 左下, j == n - 1 - i
同类型的还有一道题 1572,可以一起做。
时间O(mn)
空间O(1)
Java实现
1 class Solution { 2 public boolean checkXMatrix(int[][] grid) { 3 int m = grid.length; 4 int n = grid[0].length; 5 for (int i = 0; i < m; i++) { 6 for (int j = 0; j < n; j++) { 7 if (i == j || j == n - 1 - i) { 8 if (grid[i][j] == 0) { 9 return false; 10 } 11 } else if (grid[i][j] != 0) { 12 return false; 13 } 14 } 15 } 16 return true; 17 } 18 }
标签:elements,return,Matrix,矩阵,Check,grid,LeetCode,matrix From: https://www.cnblogs.com/cnoodle/p/17077658.html