1. 程式人生 > >840. Magic Squares In Grid ——weekly contest 86

840. Magic Squares In Grid ——weekly contest 86

AS IV SQ div color att scu turn sin

題目鏈接: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