Question:

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],
  2. [9,5,1,9],
  3. [2,7,6,2]]
  4. Output: 1
  5. Explanation:
  6. The following subgrid is a 3 x 3 magic square:
  7. 438
  8. 951
  9. 276
  10. while this one is not:
  11. 384
  12. 519
  13. 762
  14. In total, there is only one magic square inside the given grid.

Solution:

  1. /**
  2. * @param {number[][]} grid
  3. * @return {number}
  4. */
  5. var numMagicSquaresInside = function(grid) {
  6. if (!grid || grid.length < 3 || grid[0].length < 3) return 0;
  7. let row = grid.length;
  8. let col = grid[0].length;
  9. let count = 0;
  10. for (let r = 1; r < row - 1; r++) {
  11. for (let c = 1; c < col - 1; c++) {
  12. if (grid[r][c] === 5) {
  13. if (!validSurroundNum(grid,r,c)) continue;
  14. if (grid[r-1][c-1] + grid[r+1][c+1] !== 10) continue; // left top, right bottom = 10
  15. if (grid[r+1][c-1] + grid[r-1][c+1] !== 10) continue; // left bottom, right top =10
  16. if (grid[r-1][c-1] + grid[r-1][c] + grid[r-1][c+1] !== 15) continue; // top row = 15
  17. if (grid[r+1][c-1] + grid[r+1][c] + grid[r+1][c+1] !== 15) continue; // bottom row = 15
  18. if (grid[r-1][c-1] + grid[r][c-1] + grid[r+1][c-1] !== 15) continue; // left col = 15
  19. if (grid[r-1][c+1] + grid[r][c+1] + grid[r+1][c+1] !== 15) continue; // right col = 15
  20. count += 1;
  21. }
  22. }
  23. }
  24. return count;
  25. };
  26. function validSurroundNum(grid, x,y) {
  27. let set = new Set();
  28. for (let i = -1; i < 1; i++) {
  29. for (let j = -1; j < 1; j++) {
  30. if (set.has(grid[x+i][y+j]) || grid[x+i][y+j] < 1 || grid[x+i][y+j] > 9) {
  31. return false;
  32. } else {
  33. set.add(grid[x+i][y+j]);
  34. }
  35. }
  36. }
  37. return true;
  38. }

Runtime: 52 ms, faster than 100.00% of JavaScript online submissions for Magic Squares In Grid.