1918. Counting square
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
There is a matrix of size R rows by C columns. Each element in the matrix is either `0' or `1'. A square is called magic square if it meets the following three conditions.
The elements on the four borders are all `1'.
Inside the square (excluding the elements on the borders), the number of 1's and the number of 0's are different at most by 1.
The size of the square is at least 2 by 2. Now given the matrix, please tell me how many magic square are there in the matrix.
Input
The input begins with a line containing an integer T , the number of test cases. Each case begins with two integers R , C (1 ≤ R, C ≤ 300) , representing the size of the matrix. Then R lines follow. Each contains C integers, either `0' or `1'. The integers are separated by a single space.
Output
For each case, output the number of magic square in a single line.
Sample Input
3 4 4 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 5 5 1 0 1 1 1 1 0 1 0 1 1 1 0 1 1 1 0 0 1 1 1 1 1 1 1 2 2 1 1 1 1
Sample Output
3 21
// Problem#: 1918 // Submission#: 3577951 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include <stdio.h> short G[305][305]; short row1[305][305], col1[305][305]; int sum[305][305]; int h, w; int ans; void init() { int last1; for (int i = 0; i < h; i++) { last1 = -1; for (int j = w - 1; j >= 0; j--) { if (G[i][j] == -1) last1 = -1; else if (last1 == -1) last1 = j; row1[i][j] = last1; } } for (int i = 0; i < w; i++) { last1 = -1; for (int j = h - 1; j >= 0; j--) { if (G[j][i] == -1) last1 = -1; else if (last1 == -1) last1 = j; col1[j][i] = last1; } } sum[0][0] = G[0][0]; for (int i = 1; i < h; i++) sum[i][0] = sum[i - 1][0] + G[i][0]; for (int i = 1; i < w; i++) sum[0][i] = sum[0][i - 1] + G[0][i]; for (int i = 1; i < h; i++) for (int j = 1; j < w; j++) sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + G[i][j]; } inline int abs(int a) {if (a < 0) return -a; return a;} inline void cal(int si, int sj) { int li = si + 1, lj = sj + 1; while (li < h && lj < w && G[si][lj] == 1 && G[li][sj] == 1) { if (lj <= row1[li][sj] && li <= col1[si][lj]) if (abs(sum[li - 1][lj - 1] - sum[si][lj - 1] - sum[li - 1][sj] + sum[si][sj]) <= 1) ans++; lj++; li++; } } int main() { int caseNum; scanf("%d", &caseNum); while (caseNum--) { scanf("%d%d\n", &h, &w); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { scanf("%d", &G[i][j]); if (G[i][j] == 0) G[i][j] = -1; } } ans = 0; init(); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (G[i][j] == 1) cal(i, j); printf("%d\n", ans); } return 0; }