LeetCode-Magic Squares In Grid

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82425028

Description:
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:
4 3 8
9 5 1
2 7 6

while this one is not:
3 8 4
5 1 9
7 6 2

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

题意:给定一个二维数组,要求找出其所有的3X3子数组,使其满足每行元素之和、每列元素之和及两条对角线元素之和相等,返回满足这样的条件的子数组的个数;

解法:需要注意的是题目中强调这3X3的数组中的每个元素不一样并且值在[1,9]这个区间;这道题的解法就是依次遍历所有的3X3子数组,判断其是否符合题目要求的,最后返回满足的个数;

Java
class Solution {
    public int numMagicSquaresInside(int[][] grid) {
        int result = 0;
        if (grid.length < 3 || grid[0].length < 3) {
            return result;
        }
        for (int i = 0; i + 2 < grid.length; i++) {
            for (int j = 0; j + 2 < grid[i].length; j++) {
                result = isOneToNight(grid, i, i + 2, j, j + 2) && 
                    isMagicSquare(grid, i, i + 2, j, j + 2) ? result + 1 : result;
            }
        }
        return result;
    }

    private boolean isMagicSquare(int[][] grid, int stR, int edR, int stC, int edC) {
        if (grid[stR][stC] + grid[stR][stC + 1] + grid[stR][stC + 2] == 15 &&
            grid[stR + 1][stC] + grid[stR + 1][stC + 1] + grid[stR + 1][stC + 2] == 15 &&
            grid[stR + 2][stC] + grid[stR + 2][stC + 1] + grid[stR + 2][stC + 2] == 15 &&
            grid[stR][stC] + grid[stR + 1][stC] + grid[stR + 2][stC] == 15 &&
            grid[stR][stC + 1] + grid[stR + 1][stC + 1] + grid[stR + 2][stC + 1] == 15 &&
            grid[stR][stC + 2] + grid[stR + 1][stC + 2] + grid[stR + 2][stC + 2] == 15 &&
            grid[stR][stC] + grid[stR + 1][stC + 1] + grid[stR + 2][stC + 2] == 15 &&
            grid[stR][stC + 2] + grid[stR + 1][stC + 1] + grid[stR + 2][stC] == 15) {
            return true;
        }
        return false;
    }

    private boolean isOneToNight(int[][] grid, int stR, int edR, int stC, int edC) {
        for (int i = stR; i <= edR; i++) {
            for (int j = stC; j <= edC; j++) {
                if (grid[i][j] >= 10) {
                    return false;
                }
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82425028