← Home

840. Magic Squares In Grid

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
840

The trick here is to name the state correctly, then let the implementation follow. For 840. Magic Squares In Grid, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are numMagicSquaresInside.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Magic Squares In Grid.
02//Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Magic Squares In Grid.
03
04class Solution {
05public:
06    int numMagicSquaresInside(vector<vector<int>>& grid) {
07        int m = grid.size(), n = grid[0].size();
08        if(m < 3 || n < 3) return 0;
09        vector<vector<int>> hrz(m-3+1, vector<int>(n-3+1, 0));
10        vector<vector<int>> vtc(m-3+1, vector<int>(n-3+1, 0));
11        //diagonal from left-top to right-bottom
12        vector<vector<int>> lt(m-3+1, vector<int>(n-3+1, 0));
13        //diagonal from right-top to left-bottom
14        vector<vector<int>> rt(m-3+1, vector<int>(n-3+1, 0));
15        int ans = 0;
16        
17        for(int i = 0; i < m; i++){
18            for(int j = 0; j < n; j++){
19                // cout << grid[i][j] << " ";
20            }
21            // cout << endl;
22        }
23        // cout << endl;
24        
25        for(int i = 0; i < m-3+1; i++){
26            for(int j = 0; j < n-3+1; j++){
27                if(j == 0){
28                    hrz[i][j] = grid[i][0]+grid[i][1]+grid[i][2];
29                }else{
30                    //window range: [j, j+3-1]
31                    hrz[i][j] = hrz[i][j-1]+grid[i][j+3-1]-grid[i][j-1];
32                }
33                // cout << hrz[i][j] << " ";
34            }
35            // cout << endl;
36        }
37        // cout << endl;
38        
39        for(int i = 0; i < m-3+1; i++){
40            for(int j = 0; j < n-3+1; j++){
41                // cout << "i: " << i << ", j: " << j << endl;
42                if(i == 0){
43                    vtc[i][j] = grid[0][j]+grid[1][j]+grid[2][j];
44                }else{
45                    //window range: [i, i+3-1]
46                    vtc[i][j] = vtc[i-1][j]+grid[i+3-1][j]-grid[i-1][j];
47                }
48                // cout << vtc[i][j] << " ";
49            }
50            // cout << endl;
51        }
52        // cout << endl;
53        
54        for(int i = 0; i < m-3+1; i++){
55            for(int j = 0; j < n-3+1; j++){
56                // cout << "i: " << i << ", j: " << j << endl;
57                if(i == 0 || j == 0){
58                    lt[i][j] = grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2];
59                }else{
60                    //window range: [i, i+2] * [j, j+2]
61                    lt[i][j] = lt[i-1][j-1]+grid[i+2][j+2]-grid[i-1][j-1];
62                }
63                // cout << lt[i][j] << " ";
64            }
65            // cout << endl;
66        }
67        // cout << endl;
68        
69        for(int i = 0; i < m-3+1; i++){
70            for(int j = 0; j < n-3+1; j++){
71                //(i,j) is the left-top corner of the magic square
72                //(i,j+2) is the right-top corner
73                if(i == 0 || j+2 == n-1){
74                    rt[i][j] = grid[i+2][j]+grid[i+1][j+1]+grid[i][j+2];
75                }else{
76                    rt[i][j] = rt[i-1][j+1]+grid[i+2][j]-grid[i-1][j+3];
77                }
78                // cout << rt[i][j] << " ";
79            }
80            // cout << endl;
81        }
82        // cout << endl;
83        
84        for(int i = 0; i < m-3+1; i++){
85            for(int j = 0; j < n-3+1; j++){
86                int mul = 1;
87                for(int x = i; x < i+3; x++){
88                    for(int y = j; y < j+3; y++){
89                        mul *= grid[x][y];
90                    }
91                }
92                if(mul == 362880 && hrz[i][j] == 15 && vtc[i][j] == 15 && lt[i][j] == 15 && rt[i][j] == 15){
93                    ans++;
94                }
95            }
96        }
97        
98        return ans;
99    }
100};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.