Counting square

Problem 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
2
1
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 
 5 const int maxn = 310;
 6 const int inf = 1<<29;
 7 int mat[maxn][maxn];
 8 int sum[maxn][maxn];
 9 int cnt,n,m;
10 
11 bool check(int x1, int y1, int x2, int y2)
12 {
13     int a = sum[x2][y2] - sum[x1-1][y2] - sum[x2][y1-1] + sum[x1-1][y1-1];
14     int b = sum[x2-1][y2-1] - sum[x1][y2-1] - sum[x2-1][y1] + sum[x1][y1];
15     int tmp = (y2-y1+1)*2 + (x2-x1+1)*2 - 4;
16     if(a-b != tmp) return false;
17     int s = (y2-y1-1) * (x2-x1-1);
18     if(abs(s-2*b) > 1) return false;
19     return true;
20 }
21 void dfs(int x1, int y1, int l)
22 {
23     int x2 = x1+l, y2 = y1+l;
24     if(x2>n || y2>m) return;
25     if(check(x1, y1, x2, y2)) cnt++;
26     dfs(x1, y1, l+1);
27 }
28 
29 int main()
30 {
31     int T,i,j;
32     scanf("%d", &T);
33     while(T--)
34     {
35         cnt = 0;
36         scanf("%d%d", &n, &m);
37         memset(sum,0,sizeof(sum));
38         for(i=1; i<=n; i++)
39             for(j=1; j<=m; j++)
40             {
41                 scanf("%d", &mat[i][j]);
42                 sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + mat[i][j];
43             }
44         for(i=1; i<n; i++)
45             for(j=1; j<m; j++)
46                 if(mat[i][j]) dfs(i, j, 1);
47         printf("%d\n", cnt);
48     }
49     return 0;
50 }
递归遍历(约束条件)

 

posted @ 2013-08-08 15:52  1002liu  阅读(195)  评论(0编辑  收藏  举报