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
Idea 1. Since each row, column, both diagonals have the same sum, and the value is [1,9], 3*sum = (1+9) * 9/2 = 45, sum = 15, plus all 4 lines which cross the center (both diagonals + mid row + mid column) 4*sum = 3 * sum + 3 * A[1][1] (3 rows + 3*A[1][1]), hence A[1][1] = 5.
Time complexity: O(M * N)
Space complexity: O(1)
1 class Solution { 2 private boolean isMagicSquare(int startRow, int startCol, int[][] grid) { 3 int sum = 15; 4 int mask = 0; 5 6 if(grid[startRow + 1][startCol + 1] != 5) { 7 return false; 8 } 9 10 for(int i = 0; i < 3; ++i) { 11 12 int row = 0; 13 int col = 0; 14 for(int j = 0; j < 3; ++j) { 15 int val = grid[startRow + i][startCol + j]; 16 if(val < 0 || val > 9) { 17 return false; 18 } 19 20 if(((mask >> val)&1) == 1) { 21 return false; 22 } 23 24 mask |= 1 << val; 25 26 row += val; 27 col += grid[startRow + j][startCol + i]; 28 } 29 if(row != sum || col != sum) { 30 return false; 31 } 32 } 33 34 int diagonal = 0; 35 int oppositeDiagonal = 0; 36 for(int i = 0; i < 3; ++i) { 37 diagonal += grid[startRow + i][startCol +i]; 38 oppositeDiagonal += grid[startRow + i][startCol + 2 - i]; 39 } 40 if(diagonal != sum || oppositeDiagonal != sum) { 41 return false; 42 } 43 44 return true; 45 } 46 public int numMagicSquaresInside(int[][] grid) { 47 int result = 0; 48 for(int i = 0; i + 2 < grid.length; ++i) { 49 for(int j = 0; j + 2 < grid[0].length; ++j) { 50 if(isMagicSquare(i, j, grid)) { 51 ++result; 52 } 53 } 54 } 55 return result; 56 } 57 }