HDU4414-DFS
给一个图,寻找十字交叉的个数,十字交叉应为两个大于3的奇数交叉与正中央。图的大小很小。
使用DFS搜八连块,之后按照规则筛选出符合条件的交叉。
我的筛选规则有点蠢,先将点排序,再通过三段for循环判断。
1 #include <algorithm> 2 #include <cstring> 3 #include <ctype.h> 4 #include <cstdlib> 5 #include <cstdio> 6 #include <vector> 7 #include <string> 8 #include <queue> 9 #include <stack> 10 #include <cmath> 11 #include <set> 12 #include <map> 13 14 using namespace std; 15 16 struct Node{ 17 int x; 18 int y; 19 bool operator < (const struct Node &b) const 20 { 21 if(x <= b.x) 22 { 23 if(x == b.x) return y <= b.y; 24 else return true; 25 } 26 return false; 27 } 28 }cross[5000]; 29 30 int N,M,T; 31 char G[100100]; 32 int vis[100100]; 33 int dx[] = {1,-1,0,0},dy[] = {0,0,1,-1}; 34 int P; 35 36 void dfs(int u) 37 { 38 vis[u] = true; 39 cross[P].x = u%N;cross[P].y = u/N; 40 P++; 41 for(int i=0;i<4;i++) 42 { 43 int x = u%N + dx[i],y = u/N + dy[i]; 44 if(x >=0 && x < N && y >= 0 && y < N &&!vis[y*N+x] && G[y*N+x] == '#') 45 { 46 dfs(x+y*N); 47 } 48 } 49 } 50 51 int main() 52 { 53 while(scanf("%d ",&N) && N) 54 { 55 char s[100]; 56 for(int i=0;i<N;i++) 57 { 58 scanf("%s",s); 59 for(int j=0;j<N;j++) 60 { 61 G[i*N+j] = s[j]; 62 } 63 } 64 65 memset(vis,0,sizeof vis); 66 int ans = 0; 67 for(int i=0;i<N;i++) 68 { 69 for(int j=0;j<N;j++) 70 { 71 if(G[i*N+j] != '#' || vis[i*N+j]) continue; 72 P = 0; 73 dfs(i*N+j); 74 // printf("P=%d\n",P); 75 if(P % 2 == 0 || P < 5) continue; 76 else 77 { 78 //printf("check\n"); 79 sort(cross,cross+P); 80 /* 81 for(int i=0;i<P;i++) 82 { 83 printf("%d:(%d,%d)\n",i,cross[i].x,cross[i].y); 84 } 85 */ 86 int len = (P+1)/2,ok = 1,step = 0; 87 for(int i=0;i<(len-1)/2;i++) 88 { 89 if(cross[i].x != cross[0].x+i || cross[i].y != cross[0].y) {ok = 0;break;} 90 } 91 step += (len-1)/2; 92 for(int i=step;i < len+step;i++) 93 { 94 if(cross[i].y != (cross[step].y+i-step) 95 || cross[i].x != cross[step].x 96 || cross[step].x != cross[step-1].x+1 97 || cross[step].y != cross[step-1].y-(len-1)/2) 98 {ok = 0;break;} 99 } 100 step += len; 101 for(int i=step;i< step + (len-1)/2;i++) 102 { 103 if(cross[i].x != (cross[step].x+i-step) 104 || cross[i].y != cross[step].y 105 || cross[step].y != cross[0].y) 106 {ok = 0;break;} 107 } 108 if(ok) ans++; 109 } 110 111 } 112 } 113 printf("%d\n",ans); 114 } 115 }