[LeetCode]840. Magic Squares In Grid 解题报告(C++)
题目描述
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
题目大意
- 检查是否是 给定的矩阵中是否包含
Magic Squares
- 按要求写即可.
解题思路
方法1:
Magic Squares
中心肯定是5.- 按要求检查.注意越界检查
代码实现:
class Solution {
public:
int numMagicSquaresInside(vector<vector<int>>& grid) {
int row = grid.size();
int col = grid[0].size();
int res = 0;
for (int i = 1; i < row-1; ++i) {
for (int j = 1; j < col - 1; ++j) {
if (grid[i][j] == 5) {
if (checkMagicSquares(grid, i, j)) {
res++;
}
}
}
}
return res;
}
bool checkMagicSquares(vector<vector<int>>& g,int i,int j) {
int row = g.size();
int col = g[0].size();
if (i - 1 < 0 || i + 1 >= row || j - 1 < 0 || j + 1 >= row) {
return false;
}
for (int s = i - 1; s <= i + 1; s++) {
for (int t = j - 1; t <= j + 1; t++) {
if (g[s][t] > 9 || g[s][t] < 1) {
return false;
}
}
}
if (g[i - 1][j - 1] + g[i - 1][j] + g[i - 1][j + 1] == 15
&& g[i][j - 1] + g[i][j] + g[i][j + 1] == 15
&& g[i + 1][j - 1] + g[i + 1][j] + g[i + 1][j + 1] == 15
&& g[i - 1][j - 1] + g[i][j - 1] + g[i + 1][j - 1] == 15
&& g[i - 1][j] + g[i][j] + g[i + 1][j] == 15
&& g[i - 1][j + 1] + g[i][j + 1] + g[i + 1][j + 1] == 15
&& g[i - 1][j - 1] + g[i][j] + g[i + 1][j + 1] == 15
&& g[i - 1][j + 1] + g[i][j] + g[i + 1][j - 1] == 15
) {
return true;
}
return false;
}
};