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 };
基本上是暴力解法了,问题不大
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9193209.html
时间: 2024-11-06 07:44:56