友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

840. 矩阵中的幻方

3 x 3 的幻方是一个填充有 *从 19 * 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。

给定一个由整数组成的`row x col` 的 grid,其中有多少个 3 × 3 的 “幻方” 子矩阵?

注意:虽然幻方只能包含 1 到 9 的数字,但 grid 可以包含最多15的数字。

示例 1:

0840 01

输入: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2] 输出: 1 解释: 下面的子矩阵是一个 3 x 3 的幻方:

0840 02

而这一个不是:

0840 03

总的来说,在本示例所给定的矩阵中只有一个 3 x 3 的幻方子矩阵。

示例 2:

输入: grid = [[8]]
输出: 0

提示:

  • row == grid.length

  • col == grid[i].length

  • 1 <= row, col <= 10

  • 0 <= grid[i][j] <= 15

思路分析

  • 一刷

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 * @author D瓜哥 · https://www.diguage.com
 * @since 2026-07-29 22:40:19
 */
public int numMagicSquaresInside(int[][] grid) {
  if (grid.length < 3 || grid[0].length < 3) {
    return 0;
  }
  List<int[]> fivePoint = new ArrayList<>();
  for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
      if (grid[r][c] == 5) {
        // 靠边的 5 不要
        if (r == 0 || r == grid.length - 1
          || c == 0 || c == grid[r].length - 1) {
          continue;
        }
        fivePoint.add(new int[]{r, c});
      }
    }
  }
  if (fivePoint.isEmpty()) {
    return 0;
  }
  int result = 0;
  for (int[] five : fivePoint) {
    if (isMagic(grid, five[0], five[1])) {
      result++;
    }
  }
  return result;

}

private boolean isMagic(int[][] grid, int r, int c) {
  int n11 = grid[r - 1][c - 1];
  int n12 = grid[r - 1][c];
  int n13 = grid[r - 1][c + 1];
  int n21 = grid[r][c - 1];
  int n22 = grid[r][c];
  int n23 = grid[r][c + 1];
  int n31 = grid[r + 1][c - 1];
  int n32 = grid[r + 1][c];
  int n33 = grid[r + 1][c + 1];
  List<Integer> nums = List.of(
    n11, n12, n13,
    n21, n22, n23,
    n31, n32, n33);
  int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
  for (Integer num : nums) {
    min = Math.min(min, num);
    if (min < 1) {
      return false;
    }
    max = Math.max(max, num);
    if (max > 9) {
      return false;
    }
  }
  if (min != 1 || max != 9) {
    return false;
  }
  Set<Integer> set = Set.copyOf(nums);
  if (set.size() != 9) {
    return false;
  }
  // 行
  if (n11 + n12 + n13 != 15
    || n21 + n22 + n23 != 15
    || n31 + n32 + n33 != 15) {
    return false;
  }
  // 列
  if (n11 + n21 + n31 != 15
    || n12 + n22 + n32 != 15
    || n13 + n23 + n33 != 15) {
    return false;
  }
  // 对角线
  if (n11 + n22 + n33 != 15
    || n13 + n22 + n31 != 15) {
    return false;
  }
  return true;
}