2319. Check if Matrix Is X-Matrix Easy
1/**
2 * [2319] Check if Matrix Is X-Matrix
3 *
4 * A square matrix is said to be an X-Matrix if both of the following conditions hold:
5 * <ol>
6 * All the elements in the diagonals of the matrix are non-zero.
7 * All other elements are 0.
8 * </ol>
9 * 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.
10 *
11 * Example 1:
12 * <img alt="" src="https://assets.leetcode.com/uploads/2022/05/03/ex1.jpg" style="width: 311px; height: 320px;" />
13 * Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
14 * Output: true
15 * Explanation: Refer to the diagram above.
16 * An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
17 * Thus, grid is an X-Matrix.
18 *
19 * Example 2:
20 * <img alt="" src="https://assets.leetcode.com/uploads/2022/05/03/ex2.jpg" style="width: 238px; height: 246px;" />
21 * Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
22 * Output: false
23 * Explanation: Refer to the diagram above.
24 * An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
25 * Thus, grid is not an X-Matrix.
26 *
27 *
28 * Constraints:
29 *
30 * n == grid.length == grid[i].length
31 * 3 <= n <= 100
32 * 0 <= grid[i][j] <= 10^5
33 *
34 */
35pub struct Solution {}
36
37// problem: https://leetcode.com/problems/check-if-matrix-is-x-matrix/
38// discuss: https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/?currentPage=1&orderBy=most_votes&query=
39
40// submission codes start here
41
42impl Solution {
43 pub fn check_x_matrix(grid: Vec<Vec<i32>>) -> bool {
44 for i in 0..grid.len() {
45 for j in 0..grid.len() {
46 if i == j || i + j == grid.len() - 1 {
47 if grid[i][j] == 0 {
48 return false;
49 }
50 } else {
51 if grid[i][j] != 0 {
52 return false;
53 }
54 }
55 }
56 }
57 true
58 }
59}
60
61// submission codes end
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_2319() {
69 assert!(!Solution::check_x_matrix(vec![
70 vec![0, 0, 0, 0, 1],
71 vec![0, 4, 0, 1, 0],
72 vec![0, 0, 5, 0, 0],
73 vec![0, 5, 0, 2, 0],
74 vec![4, 0, 0, 0, 2]
75 ]));
76 assert!(Solution::check_x_matrix(vec![
77 vec![2, 0, 0, 1],
78 vec![0, 3, 1, 0],
79 vec![0, 5, 2, 0],
80 vec![4, 0, 0, 2]
81 ]));
82 }
83}
84
Back
© 2025 bowen.ge All Rights Reserved.