Because we need to put a judge once every run again full picture bfs is clearly unrealistic
And because only three points, no black and white
So you can use disjoint-set optimization
Add a piece it is judged that the situation around the four groups of
Discrimination between situations arise and answer relationship Note
1 /* 2 Written By StelaYuri 3 */ 4 #include<stdio.h> 5 #include<memory.h> 6 int N,M,dx[4]={1,0,-1,0},dy[4]={0,1,0,-1},gp[250010]; 7 char cm[505][505]; 8 int findp(int p){ 9 return p==gp[p]?p:(gp[p]=findp(gp[p])); 10 } 11 int prime(int x,int y){ 12 return x>=0&&y>=0&&x<N&&y<N; 13 } 14 int main(){ 15 int i,j,X,Y,xx,yy,ans=0,g,d1,d2; 16 char C; 17 memset(cm,'.',sizeof cm); 18 for(i=0;i<250000;i++) 19 gp[i]=i; 20 scanf("%d%d",&N,&M); 21 for(i=0;i<M;i++){ 22 scanf("%*c%c%d%d",&C,&X,&Y); 23 ans++; 24 for(g=j=0;j<4;j++){ 25 xx=X-1+dx[j]; 26 yy=Y-1+dy[j]; 27 if(prime(xx,yy)&&cm[xx][yy]==C){ 28 findp = D1 (GP [(X- . 1 ) * N + (Y- . 1 )]); 29 D2 = findp (GP [XX * N + YY]); 30 IF (! G) { // four surrounding positions If further is not found, may be combined one with the set of direct and reducing a set of answers 31 is G = . 1 ; 32 IF (! D1 = D2) { 33 is IF (D1 < D2) 34 is GP [D2] = D1; 35 the else 36 GP [D1 ] = D2; 37 [ } 38 is ans-- ; 39 } 40 the else { // four surrounding positions if a same group has been found, and only when the different sets of points where the two were combined and reduced need for a answer group 41 is IF (D1! = D2) { 42 is IF (D1 < D2) 43 is GP [D2] = D1; 44 is the else 45 GP [D1] = D2; 46 is ans-- ; 47 } 48 } 49 } 50 } 51 is cm & lt [X- . 1 ] [Y- . 1 ] = C; 52 is printf("%d\n",ans); 53 } 54 55 return 0; 56 }