目录结构
1.题目
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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/magic-squares-in-grid
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
public class Solution840 {
@Test
public void test840() {
int[][] grid = {
{4, 3, 8, 4},
{9, 5, 1, 9},
{2, 7, 6, 2}};
System.out.println(numMagicSquaresInside(grid));
}
public int numMagicSquaresInside(int[][] grid) {
int result = 0;
for (int i = 0; i <= grid.length - 3; i++) {
for (int j = 0; j <= grid[0].length - 3; j++) {
if (judge(grid, i, j)) {
result++;
}
}
}
return result;
}
public boolean judge(int[][] grid, int sR, int sC) {
if (grid[sR + 1][sC + 1] != 5) {
return false;
}
if (grid[sR][sC] + grid[sR + 1][sC + 1] + grid[sR + 2][sC + 2] != 15) {
return false;
}
if (grid[sR][sC + 2] + grid[sR + 1][sC + 1] + grid[sR + 2][sC] != 15) {
return false;
}
for (int j = sC; j < sC + 3; j++) {
int count = 0;
for (int i = sR; i < sR + 3; i++) {
count += grid[i][j];
}
if (count != 15) {
return false;
}
}
Set<Integer> set = new HashSet<>();
for (int i = sR; i < sR + 3; i++) {
int count = 0;
for (int j = sC; j < sC + 3; j++) {
count += grid[i][j];
if (1 <= grid[i][j] && grid[i][j] <= 9) {
set.add(grid[i][j]);
}
}
if (count != 15) {
return false;
}
}
if (set.size() != 9) {
return false;
}
return true;
}
}
- 时间复杂度:
- 空间复杂度: