题目链接: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
原文地址:https://www.cnblogs.com/jinjin-2018/p/9098125.html
时间: 2024-10-08 16:05:56