A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given an grid
of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: [[4,3,8,4], [9,5,1,9], [2,7,6,2]] Output: 1 Explanation: The following subgrid is a 3 x 3 magic square: 438 951 276 while this one is not: 384 519 762 In total, there is only one magic square inside the given grid.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
0 <= grid[i][j] <= 15
思路:这题就是一个考察实现的题目,注意有个数学知识,就是:横竖对角线相加,可以计算出,3*3矩阵的中心点必须是5;
其余就是要判断1: unqiue,2.横竖对角线和是15;
class Solution {
public int numMagicSquaresInside(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length;
int m = grid[0].length;
int count = 0;
for(int i = 0; i < n - 2; i++) {
for(int j = 0; j < m - 2; j++) {
if(isvalid(grid, i, j)) {
count++;
}
}
}
return count;
}
private boolean isvalid(int[][] grid, int x, int y) {
if(grid[x + 1][y + 1] != 5) {
return false;
}
if(!isunique(grid, x, y)) {
return false;
}
// all directions sum should be 15;
// (x , y) (x, y + 1), (x, y + 2);
// (x + 1,y), (x + 1, y + 1), (x + 1, y + 2);
// (x + 2,y), (x + 2, y + 1), (x + 2, y + 2);
// horizontal;
if(grid[x][y] + grid[x][y + 1] + grid[x][y + 2] != 15) return false;
if(grid[x + 1][y] + grid[x + 1][y + 1] + grid[x + 1][y + 2] != 15) return false;
if(grid[x + 2][y] + grid[x + 2][y + 1] + grid[x + 2][y + 2] != 15) return false;
// vertical;
if(grid[x][y] + grid[x + 1][y] + grid[x + 2][y] != 15) return false;
if(grid[x][y + 1] + grid[x + 1][y + 1] + grid[x + 2][y + 1] != 15) return false;
if(grid[x][y + 2] + grid[x + 1][y + 2] + grid[x + 2][y + 2] != 15) return false;
// diagonal;
if(grid[x][y] + grid[x + 1][y + 1] + grid[x + 2][y + 2] != 15) return false;
if(grid[x][y + 2] + grid[x + 1][y + 1] + grid[x + 2][y] != 15) return false;
return true;
}
private boolean isunique(int[][] grid, int x, int y) {
int[] count = new int[16];
for(int i = x; i < x + 3; i++) {
for(int j = y; j < y + 3; j++) {
count[grid[i][j]]++;
}
}
for(int i = 1; i <= 9; i++) {
if(count[i] != 1) {
return false;
}
}
return true;
}
}