Skip to content

Commit 9c1f520

Browse files
committed
Add solution #840
1 parent db16ed7 commit 9c1f520

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -647,6 +647,7 @@
647647
837|[New 21 Game](./0837-new-21-game.js)|Medium|
648648
838|[Push Dominoes](./0838-push-dominoes.js)|Medium|
649649
839|[Similar String Groups](./0839-similar-string-groups.js)|Hard|
650+
840|[Magic Squares In Grid](./0840-magic-squares-in-grid.js)|Medium|
650651
841|[Keys and Rooms](./0841-keys-and-rooms.js)|Medium|
651652
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
652653
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 840. Magic Squares In Grid
3+
* https://leetcode.com/problems/magic-squares-in-grid/
4+
* Difficulty: Medium
5+
*
6+
* A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row,
7+
* column, and both diagonals all have the same sum.
8+
*
9+
* Given a row x col grid of integers, how many 3 x 3 magic square subgrids are there?
10+
*
11+
* Note: while a magic square can only contain numbers from 1 to 9, grid may contain numbers up
12+
* to 15.
13+
*/
14+
15+
/**
16+
* @param {number[][]} grid
17+
* @return {number}
18+
*/
19+
var numMagicSquaresInside = function(grid) {
20+
const rows = grid.length;
21+
const cols = grid[0].length;
22+
23+
if (rows < 3 || cols < 3) return 0;
24+
25+
let result = 0;
26+
for (let r = 0; r <= rows - 3; r++) {
27+
for (let c = 0; c <= cols - 3; c++) {
28+
if (isMagicSquare(grid, r, c)) result++;
29+
}
30+
}
31+
32+
return result;
33+
};
34+
35+
function isMagicSquare(grid, r, c) {
36+
if (grid[r + 1][c + 1] !== 5) return false;
37+
38+
const cells = [
39+
grid[r][c], grid[r][c + 1], grid[r][c + 2],
40+
grid[r + 1][c], grid[r + 1][c + 1], grid[r + 1][c + 2],
41+
grid[r + 2][c], grid[r + 2][c + 1], grid[r + 2][c + 2]
42+
];
43+
44+
if (!cells.every(val => val >= 1 && val <= 9) || new Set(cells).size !== 9) return false;
45+
46+
return (
47+
grid[r][c] + grid[r][c + 1] + grid[r][c + 2] === 15
48+
&& grid[r + 1][c] + grid[r + 1][c + 1] + grid[r + 1][c + 2] === 15
49+
&& grid[r + 2][c] + grid[r + 2][c + 1] + grid[r + 2][c + 2] === 15
50+
&& grid[r][c] + grid[r + 1][c] + grid[r + 2][c] === 15
51+
&& grid[r][c + 1] + grid[r + 1][c + 1] + grid[r + 2][c + 1] === 15
52+
&& grid[r][c + 2] + grid[r + 1][c + 2] + grid[r + 2][c + 2] === 15
53+
&& grid[r][c] + grid[r + 1][c + 1] + grid[r + 2][c + 2] === 15
54+
&& grid[r][c + 2] + grid[r + 1][c + 1] + grid[r + 2][c] === 15
55+
);
56+
}

0 commit comments

Comments
 (0)