problem
solution:
class Solution { public: int numMagicSquaresInside(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); int cnt = 0; for(int i=1; i<m-1; ++i) { for(int j=1; j<n-1; ++j) { if(isvalid(grid, i, j)) cnt++; } } return cnt; } bool isvalid(vector<vector<int>>& grid, int i, int j) { vector<int> cnt(10); for(int x=i-1; x<=i+1; x++)//for loop errr... { for(int y=j-1; y<=j+1; y++) { int k=grid[x][y]; if(k>9 || k<0 || cnt[k]==1) return false; cnt[k] = 1; } } if(grid[i][j]!=5) return false; if(grid[i-1][j-1]+grid[i-1][j]+grid[i-1][j+1] != 15) return false; if(grid[i][j-1]+grid[i][j]+grid[i][j+1] != 15) return false; if(grid[i+1][j-1]+grid[i+1][j]+grid[i+1][j+1] != 15) return false; if(grid[i-1][j-1]+grid[i][j-1]+grid[i+1][j-1] != 15) return false; if(grid[i-1][j]+grid[i][j]+grid[i+1][j] != 15) return false; if(grid[i-1][j+1]+grid[i][j+1]+grid[i+1][j+1] != 15) return false; if(grid[i-1][j-1]+grid[i][j]+grid[i+1][j+1] != 15) return false; if(grid[i-1][j+1]+grid[i][j]+grid[i+1][j-1] != 15) return false; return true; } };
参考
1. Leetcode_easy_840. Magic Squares In Grid;
2. grandyang;
完