840. Magic Squares In Grid

Posted zhuangbijingdeboke

tags:

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

 1 class Solution 
 2 {
 3 public:
 4     int numMagicSquaresInside(vector<vector<int>>& grid) 
 5     {
 6         int count=0;
 7         int szx=grid.size();
 8         int szy=grid[0].size();
 9         for(int i=0;i<szx-2;i++)
10         {
11             for(int j=0;j<szy-2;j++)
12             {
13                 if(grid[i+1][j+1]==5&&judge(grid,i,j))
14                     count++;
15             }
16         }
17         return count;
18     }
19     
20     bool judge(vector<vector<int>> &grid,int i,int j)
21     {
22         for(int x=i;x<i+3;x++)                 //judge cur num biggerthan 9 or not,if yes,return false
23         {
24             for(int y=j;y<j+3;y++)
25             {
26                 if(grid[x][y]>9)
27                     return false;
28             }
29         }
30         for(int x=i;x<i+3;x++)                //judge every row‘s sum is 15 or not
31         {
32             if(grid[x][j]+grid[x][j+1]+grid[x][j+2]!=15)
33                 return false;
34         }
35         for(int y=j;y<j+3;y++)               //judge every col‘s sum is 15 or not
36         {
37             if(grid[i][y]+grid[i+1][y]+grid[i+2][y]!=15)
38                 return false;
39         }
40         if(grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2]!=15)   //judge diagonals
41             return false;
42         if(grid[i+2][j]+grid[i+1][j+1]+grid[i][j+2]!=15)
43             return false;
44         return true;
45     }
46 };

基本上是暴力解法了,问题不大

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

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