How Many Squares? CodeForces - 11C
考察:模拟(?)
思路:
对于当前点,先找以它为顶点第一类正方形边长,再找第二类正方形边长.最后计算一下以它为顶点的连通块1的数目,如果1的个数 = (边长-1)*4,那么这就是一类正方形.
还是要多动脑啊,不想没用啊TAT
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 const int N = 255; 6 int n,m; 7 int xx[8] = {-1,1,0,0,-1,-1,1,1}; 8 int yy[8] = {0,0,-1,1,-1,1,-1,1}; 9 char s[N][N]; 10 int dfs_1(int x,int y) 11 { 12 int a = 1,b = 1,c = 1,d = 1; 13 while(x+1<=n&&s[x+1][y]=='1') x++,a++; 14 while(y+1<=m&&s[x][y+1]=='1') y++,b++; 15 while(x-1>0&&s[x-1][y]=='1') x--,c++; 16 while(y-1>0&&s[x][y-1]=='1') y--,d++; 17 if(a==b&&c==d&&a==c) return a; 18 return 0; 19 } 20 int dfs_2(int x,int y) 21 { 22 int a = 1,b = 1,c = 1,d = 1; 23 while(x+1<=n&&y-1>0&&s[x+1][y-1]=='1') x++,y--,a++; 24 while(x+1<=n&&y+1<=m&&s[x+1][y+1]=='1') x++,y++,b++; 25 while(x-1>0&&y+1<=m&&s[x-1][y+1]=='1') x--,y++,c++; 26 while(x-1>0&&y-1>0&&s[x-1][y-1]=='1') x--,y--,d++; 27 if(a==b&&b==c&&c==d) return a; 28 return 0; 29 } 30 int dfs_3(int x,int y) 31 { 32 s[x][y] = '0'; 33 int w = 1; 34 for(int i=0;i<8;i++) 35 { 36 int dx = x+xx[i],dy = y+yy[i]; 37 if(dx>0&&dx<=n&&dy>0&&dy<=m&&s[dx][dy]=='1') 38 w+=dfs_3(dx,dy); 39 } 40 return w; 41 } 42 int main() 43 { 44 int T; 45 scanf("%d",&T); 46 while(T--) 47 { 48 int ans = 0; 49 scanf("%d%d",&n,&m); 50 for(int i=1;i<=n;i++) scanf("%s",s[i]+1); 51 for(int i=1;i<=n;i++) 52 for(int j=1;j<=m;j++) 53 if(s[i][j]=='1') 54 { 55 int a = dfs_1(i,j); 56 int b = dfs_2(i,j); 57 int w = dfs_3(i,j);//返回(i,j)连通块1的个数. 58 if(w==4*(a-1)||w==4*(b-1)) ans++; 59 } 60 printf("%d\n",ans); 61 } 62 return 0; 63 }