[LeetCode]840. Magic Squares In Grid 解题报告(C++)

[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. 1 <= grid.length <= 10
  2. 1 <= grid[0].length <= 10
  3. 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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值