840. Magic Squares In Grid ——weekly contest 86

Posted jinjin-2018

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了840. Magic Squares In Grid ——weekly contest 86相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/magic-squares-in-grid/description

attention:注意给定的数字不一定是1-9。

time:5ms

本人的解法过于粗糙,看出了中间必须是5,然后比较每行每列每对角线的值是否相等。

class Solution {
public:
    int numMagicSquaresInside(vector<vector<int>>& grid) {
        int n = grid.size();
        int res = 0;
        for(int i = 0; i < n - 2; i++){
            for(int j = 0; j < n - 2; j++){
                int sign = 0;
                for(int k = i; k < i+3; k++){
                    for(int l = j; l < j+3; l++){
                        if(grid[k][l] > 9 || grid[k][l] < 1){
                            sign = 1;
                            break;
                        }
                    }
                    if(sign){
                        break;
                    }
                }
                if(sign){
                    continue;
                }
                if(grid[i+1][j+1] == 5){

                    if(grid[i][j]+grid[i+2][j+2]==grid[i+2][j]+grid[i][j+2]&&grid[i+2][j]+grid[i][j+2]==grid[i+1][j]+grid[i+1][j+2]&&grid[i+2][j]+grid[i][j+2]==grid[i][j+1]+grid[i+2][j+1]){
                        
                        if(grid[i][j]+grid[i+1][j]+grid[i+2][j]==grid[i][j+2]+grid[i+1][j+2]+grid[i+2][j+2]&&grid[i][j]+grid[i+1][j]+grid[i+2][j]==15){
                            if(grid[i][j]+grid[i][j+1]+grid[i][j+2]==grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2]&&grid[i][j]+grid[i][j+1]+grid[i][j+2]==15){
                                res++;
                            }
                        }
                    }
                }
            }
        }
        return res;
    }
};

下面是看到的别人写的更简单的实现:

https://leetcode.com/problems/magic-squares-in-grid/discuss/133874/Python-5-and-43816729

 

以上是关于840. Magic Squares In Grid ——weekly contest 86的主要内容,如果未能解决你的问题,请参考以下文章

840. Magic Squares In Grid

[LeetCode] 840. Magic Squares In Grid_Easy

840. Magic Squares In Grid (5月27日)

Leetcode 840. Magic Squares In Grid

148.Magic Squares In Grid

Magic Squares