Skip to content

Instantly share code, notes, and snippets.

@BiruLyu
Created May 27, 2018 03:42
Show Gist options
  • Save BiruLyu/261d654d89f5aade4af89aa4e0a614d4 to your computer and use it in GitHub Desktop.
Save BiruLyu/261d654d89f5aade4af89aa4e0a614d4 to your computer and use it in GitHub Desktop.
class Solution {
public int numMagicSquaresInside(int[][] grid) {
if (grid == null || grid.length < 3 || grid[0].length < 3) return 0;
int m = grid.length, n = grid[0].length;
boolean[] visited = new boolean[9];
int[] rows = new int[3];
int[] cols = new int[3];
int[] diags = new int[2];
boolean flag = false;
int count = 0;
for (int i = 0; i <= m - 3; i++) {
for (int j = 0; j <= n - 3; j++) {
for (int r = 0; r < 3; r++) {
for (int l = 0; l < 3; l++) {
int cur = grid[r + i][l + j];
if ((cur <= 9 && cur >= 1 ) && !visited[cur - 1]) {
rows[r] += cur;
cols[l] += cur;
if (r == l) diags[0] += cur;
if (r + l == 2) diags[1] += cur;
} else {
flag = true;
break;
}
}
if (flag) break;
}
if (!flag) {
int first = rows[0];
boolean equal = true;
for (int ii = 0; ii < 3; ii++) {
if (rows[ii] != first || cols[ii] != first) {
equal = false;
break;
}
}
if (diags[0] != first || diags[1] != first) {
equal = false;
}
if (equal) count++;
}
rows = new int[3];
cols = new int[3];
diags = new int[2];
flag = false;
}
}
return count;
}
}840. Magic Squares In Grid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment