840. magic squares in grid
今天起的很早==
3*3覺得不寫迴圈好像也沒差
又是一坨
反正只check中間是5
應該有快一點
剩下性質懶得想
但不管中間是不是5應該也會過
吧?
class Solution {
public:
int numMagicSquaresInside(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
vector<int> num(10, 0);
num[0] = 1;
if(n < 3 or m < 3) return 0;
int sum = 15;
int res = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(grid[i][j] == 5){
res += check(num, grid, i, j);
}
}
}
return res;
}
int check(vector<int> num, vector<vector<int>>& grid, int& i, int& j){
int n = grid.size(), m = grid[0].size();
if(i == 0 or i == (n-1) or j == 0 or j == (m-1) ){
return 0;
}
for(int x = i-1; x < i+2; x++){
for(int y = j-1; y < j+2; y++){
if(grid[x][y] < 10){
num[grid[x][y]] = 1;
}
else return 0;
}
}
for(auto x: num){
if(x != 1) return 0;
}
if ((grid[i-1][j] + grid[i+1][j]) != 10 or\
(grid[i][j-1] + grid[i][j+1]) != 10 or\
(grid[i-1][j-1] + grid[i+1][j+1]) != 10 or\
(grid[i-1][j+1] + grid[i+1][j-1]) != 10){
return 0;
}
if( (grid[i-1][j-1] + grid[i-1][j] + grid[i-1][j+1]) != 15 or\
(grid[i+1][j-1] + grid[i+1][j] + grid[i+1][j+1]) != 15 or\
(grid[i-1][j-1] + grid[i][j-1] + grid[i+1][j-1]) != 15 or\
(grid[i-1][j+1] + grid[i][j+1] + grid[i+1][j+1]) != 15 ){
return 0;
}
j++;
return 1;
}
};