# LeetCode算法题-Magic Squares In Grid（Java实现）

### 01 看题和准备

4 3 8

9 5 1

2 7 6

3 8 4

5 1 9

7 6 2

• 1 <= grid.length <= 10

• 1 <= grid [0] .length <= 10

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

### 02 解题

（1）每行、每列、两条对角线上的元素之和相等。

（2）每个元素的取值范围为：[1,9]。

（3）魔方中的任意元素不能出现重复值，即为1到9的随机排列。

public int numMagicSquaresInside(int[][] grid) {
int row = grid.length, col = grid[0].length;
if (row < 2 || col < 2) {
return 0;
}
int count = 0;
for (int i=0; i<row-2; i++) {
for (int j=0; j<col-2; j++) {
int n = grid[i][j], n2 = grid[i][j+1], n3 = grid[i][j+2];
int n4 = grid[i+1][j], n5 = grid[i+1][j+1], n6 = grid[i+1][j+2];
int n7 = grid[i+2][j], n8 = grid[i+2][j+1], n9 = grid[i+2][j+2];
// 1 <= grid[i][j] <= 9，且不能出现重复值
if ((n^n2^n3^n4^n5^n6^n7^n8^n9) != (1^2^3^4^5^6^7^8^9)) {
continue;
}
// 三行三列外加两对角线，判断和
int sum = n+n2+n3;
int sum2 = n4+n5+n6;
int sum3 = n7+n8+n9;
int sum4 = n+n4+n7;
int sum5 = n2+n5+n8;
int sum6 = n3+n6+n9;
int sum7 = n+n5+n9;
int sum8 = n3+n5+n7;
if (sum == sum2 && sum2 == sum3 && sum3 == sum4
&& sum4 == sum5 && sum5 == sum6 && sum6 == sum7
&& sum7 == sum8) {
count++;
}
}
}
return count;
}

### 03 小结

posted @ 2019-05-06 08:34 程序员小川 阅读(...) 评论(...) 编辑 收藏