840-矩阵中的幻方

3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。
给定一个由整数组成的 grid,其中有多少个 3 × 3 的 “幻方” 子矩阵?(每个子矩阵都是连续的)。

示例:

输入: [[4,3,8,4],
   [9,5,1,9],
   [2,7,6,2]]
输出: 1

解释:

下面的子矩阵是一个 3 x 3 的幻方:
438
951
276
而这一个不是:
384
519
762
总的来说,在本示例所给定的矩阵中只有一个 3 x 3 的幻方子矩阵。

提示:

1 <= grid.length <= 10
1 <= grid[0].length <= 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
class Solution {
public int numMagicSquaresInside(int[][] grid) {
int ret = 0;
int sum = 15;
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < grid.length - 2; i++) {
for (int j = 0; j < grid[i].length - 2; j++) {
hashMap.clear();
int a11 = grid[i][j];
int a12 = grid[i][j + 1];
int a13 = grid[i][j + 2];
int a21 = grid[i + 1][j];
int a22 = grid[i + 1][j + 1];
int a23 = grid[i + 1][j + 2];
int a31 = grid[i + 2][j];
int a32 = grid[i + 2][j + 1];
int a33 = grid[i + 2][j + 2];
if (a22 != 5)
continue;
hashMap.put(a11, 1);
hashMap.put(a12, 1);
hashMap.put(a13, 1);
hashMap.put(a21, 1);
hashMap.put(a22, 1);
hashMap.put(a23, 1);
hashMap.put(a31, 1);
hashMap.put(a32, 1);
hashMap.put(a33, 1);
if (hashMap.size() != 9) {
continue;
}
boolean flag = true;
for (Map.Entry<Integer, Integer> e : hashMap.entrySet()) {
if (e.getKey() > 9 || e.getKey() < 1) {
flag = false;
break;
}
}
if (!flag)
continue;
if (a11 + a12 + a13 != sum)
continue;
if (a21 + a22 + a23 != sum)
continue;
if (a31 + a32 + a33 != sum)
continue;
if (a11 + a21 + a31 != sum)
continue;
if (a12 + a22 + a32 != sum)
continue;
if (a13 + a23 + a33 != sum)
continue;
if (a11 + a22 + a33 != sum)
continue;
if (a13 + a22 + a31 != sum)
continue;
ret++;
}
}
return ret;
}
}

这道题真的是无脑,遍历可以解决的题还扔出来。。。