840. Magic Squares In Grid
问题:
给定数组,判断其中含有多少个3阶幻方
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 <= grid.length <= 10 1 <= grid[0].length <= 10 0 <= grid[i][j] <= 15
解法:
幻方的特点是,全体数和=3X幻和,幻和=3×中心数
在基本三阶幻方中,幻和=1+2+...+9=45/3=15,所以中心数=5
因此只要从[1,1]开始判断中间数为5,再进一步判断是否为幻方。
进一步判断:
首先可使用二进制数来判断是否该矩阵是由1~9的组成。
再判断通过中心的4组对角值和为10,&& 第一行和第一列和为15。
代码参考:
1 class Solution { 2 public: 3 bool isMagic(int i, int j, vector<vector<int>>& grid){ 4 int chknum = 0; 5 for(int a=i-1; a<=i+1; a++){ 6 for(int b=j-1; b<=j+1; b++){ 7 if(grid[a][b]>0 && grid[a][b]<10) 8 chknum |= 1<<(grid[a][b]-1); 9 } 10 } 11 if(chknum!=0b111111111) return false; 12 if(grid[i-1][j-1]+grid[i+1][j+1]==10 && grid[i][j-1]+grid[i][j+1]==10 && 13 grid[i-1][j]+grid[i+1][j]==10 && grid[i-1][j+1]+grid[i+1][j-1]==10 && 14 grid[i-1][j-1]+grid[i-1][j]+grid[i-1][j+1]==15 && 15 grid[i-1][j-1]+grid[i][j-1]+grid[i+1][j-1]==15) 16 return true; 17 else return false; 18 } 19 int numMagicSquaresInside(vector<vector<int>>& grid) { 20 int N=grid.size(); 21 int res=0; 22 for(int i=1; i<N-1; i++){ 23 for(int j=1; j<N-1; j++){ 24 if(grid[i][j]==5 && isMagic(i,j,grid)){ 25 res++; 26 j++; 27 } 28 } 29 } 30 return res; 31 } 32 };