3 x 3 的幻方是一个填充有从 1 到 9 的不同数字的 3 x 3 矩阵,其中每行,每列以及两条对角线上的各数之和都相等。
给定一个由整数组成的 grid
,其中有多少个 3 × 3 的 “幻方” 子矩阵?(每个子矩阵都是连续的)。
示例:
输入: [[4,3,8,4], [9,5,1,9], [2,7,6,2]] 输出: 1 解释: 下面的子矩阵是一个 3 x 3 的幻方: 438 951 276 而这一个不是: 384 519 762 总的来说,在本示例所给定的矩阵中只有一个 3 x 3 的幻方子矩阵。
提示:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
0 <= grid[i][j] <= 15
题目要求1-9组成3*3的矩阵,每个数字都要用上,所以对应的每行每列值都为15, 故中间值须为5
这样可以去除大部分无用运算
其他只要注意边界条件,依次判断即可
class Solution {
public:
int numMagicSquaresInside(vector<vector<int>>& grid) {
if (grid.size() < 3 || grid[0].size() < 3) {
return 0;
}
int total = 15;
int count = 0;
for(int i = 2; i < grid.size(); ++i) {
JudgeCol(grid, i, total, 2, count);
}
return count;
}
void JudgeCol(vector<vector<int>>& grid, int row, int total, int col, int& count) {
int row_begin = row - 2, col_begin = col - 2;
while (col < grid[0].size()) {
if (grid[row_begin + 1][col - 1] != 5) {
col += 1;
continue;
}
vector<bool> dict(10, false);
bool equal = Lines(grid, row_begin, row, col - 2, col, total, dict);
bool not_all_used = AllNumberNotUsed(dict);
if (!equal || not_all_used) {
col += 1;
continue;
}
int s = grid[row_begin][col - 2] + grid[row_begin + 1][col - 1] +
grid[row_begin + 2][col];
if (s != total){
col += 1;
continue;
}
int t = grid[row_begin][col] + grid[row_begin + 1][col - 1] +
grid[row_begin + 2][col - 2];
if (t != total){
col += 1;
continue;
}
count += 1;
col += 1;
}
}
bool AllNumberNotUsed(vector<bool>& dict) {
for (int i = 1;i < dict.size(); ++i) {
if (dict[i] == false) {
return true;
}
}
return false;
}
bool Lines(vector<vector<int>>& grid, int s_begin, int s_end, int t_begin,int t_end, int total, vector<bool>& dict) {
for (int i = s_begin; i <= s_end; ++i) {
int s = 0;
for (int j = t_begin; j <= t_end; ++j) {
if (grid[i][j] > 9) {
return false;
}
s += grid[i][j];
dict[grid[i][j]] = true;
}
if (s != total) {
return false;
}
}
for (int j = t_begin; j <= t_end; ++j) {
int t = 0;
for (int i = s_begin; i <= s_end; ++i) {
t += grid[i][j];
}
if (t != total) {
return false;
}
}
return true;
}
};