../ Competitive Programming
-rw-r--r--aguang1.7 KiB2 min read

Leet Code Daily 2024-08-09 - Magic Squares in Grid

Code

c++
const vector<int> kAllowedVals = {
    1, 2, 3, 4, 5, 6, 7, 8, 9,
};

class Solution {
public:
    int numMagicSquaresInside(vector<vector<int>>& grid) {
        const int rows = grid.size(), cols = grid[0].size();
        int ret = 0;
        for (int r = 0; r + 2 < rows; r++) {
            for (int c = 0; c + 2 < cols; c++) {
                bool ok = true;
                const auto s =
                    grid[r][c] + grid[r + 1][c + 1] + grid[r + 2][c + 2];
                if (s !=
                    (grid[r][c + 2] + grid[r + 1][c + 1] + grid[r + 2][c])) {
                    ok = false;
                }
                for (int k = 0; k < 2 && ok; k++) {
                    if (s != (grid[r + k][c] + grid[r + k][c + 1] +
                              grid[r + k][c + 2])) {
                        ok = false;
                    }
                    if (s != (grid[r][c + k] + grid[r + 1][c + k] +
                              grid[r + 2][c + k])) {
                        ok = false;
                    }
                }
                if (ok) {
                    vector<int> vals;
                    for (int i = 0; i < 3; i++) {
                        for (int j = 0; j < 3; j++) {
                            vals.push_back(grid[r + i][c + j]);
                        }
                    }
                    sort(vals.begin(), vals.end());
                    if (vals == kAllowedVals) {
                        ret++;
                    }
                }
            }
        }
        return ret;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window