hdu 1198 Farm Irrigation

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1066    Accepted Submission(s): 472


      听我一同学说他做这一道题时用的是并查集,不过我觉得这一题用广搜更容易,一个一个的扫描,将所有与这个集合里面元素有关的都放进队列里,看能形成几个集合。
代码:

 

  
    
1
2   // 15ms
3   #include < stdio.h >
4 #include < queue >
5 using namespace std;
6 typedef struct node
7 {
8 char data;
9 int x, y;
10
11 }NODE;
12 int mark[ 60 ][ 60 ]; char a[ 60 ][ 60 ];
13 int main()
14 {
15 int z[ 11 ][ 4 ][ 2 ] = {{{ - 1 , 0 },{ 0 , - 1 },{ 0 , 0 },{ 0 , 0 }},
16 {{ 0 , - 1 },{ 1 , 0 },{ 0 , 0 },{ 0 , 0 }},
17 {{ - 1 , 0 },{ 0 , 1 },{ 0 , 0 },{ 0 , 0 }},
18 {{ 1 , 0 },{ 0 , 1 },{ 0 , 0 },{ 0 , 0 }},
19 {{ 0 , 1 },{ 0 , - 1 },{ 0 , 0 },{ 0 , 0 }},
20 {{ - 1 , 0 },{ 1 , 0 },{ 0 , 0 },{ 0 , 0 }},
21 {{ - 1 , 0 },{ 1 , 0 },{ 0 , - 1 },{ 0 , 0 }},
22 {{ - 1 , 0 },{ 0 , 1 },{ 0 , - 1 },{ 0 , 0 }},
23 {{ 1 , 0 },{ - 1 , 0 },{ 0 , 1 },{ 0 , 0 }},
24 {{ 1 , 0 },{ 0 , 1 },{ 0 , - 1 },{ 0 , 0 }},
25 {{ 0 , 1 },{ 0 , - 1 },{ 1 , 0 },{ - 1 , 0 }}};
26 NODE cur,next;
27 int m,n,i,j,count,k,tag,t;
28 while (scanf( " %d%d " , & m, & n) != EOF)
29 {
30
31 if (m < 0 || n < 0 )
32 break ;
33 count = 0 ;
34 for (i = 0 ;i < m;i ++ )
35 {
36 getchar();
37 for (j = 0 ;j < n;j ++ )
38 {
39 scanf( " %c " , & a[i][j]);
40 mark[i][j] = 0 ;
41 }
42 }
43 queue < NODE > qu;
44 for (i = 0 ;i < m;i ++ )
45 for (j = 0 ;j < n;j ++ )
46 {
47 if ( ! mark[i][j])
48 {
49 count ++ ;
50 mark[i][j] = 1 ;
51 cur.data = a[i][j];
52 cur.x = j;
53 cur.y = i;
54 qu.push(cur);
55 while ( ! qu.empty())
56 {
57 cur = qu.front();
58 qu.pop();
59 for (k = 0 ;k < 4 ;k ++ )
60 {
61 next.x = cur.x + z[cur.data - ' A ' ][k][ 0 ];
62 next.y = cur.y + z[cur.data - ' A ' ][k][ 1 ];
63 tag = 0 ;
64 if (next.x >= 0 && next.x < n && next.y >= 0 && next.y < m &&! mark[next.y][next.x])
65 {
66 next.data = a[next.y][next.x];
67 for (t = 0 ;t < 4 ;t ++ )
68 {
69 int x,y;
70 x = next.x + z[next.data - ' A ' ][t][ 0 ];
71 y = next.y + z[next.data - ' A ' ][t][ 1 ];
72 if (x == cur.x && y == cur.y)
73 {
74 tag = 1 ;
75 break ;
76 }
77 }
78 if (tag)
79 {
80 mark[next.y][next.x] = 1 ;
81 qu.push(next);
82 }
83 }
84 }
85 }
86 }
87 }
88 printf( " %d\n " ,count);
89 }
90 return 0 ;
91 }
92
93
94

 

你可能感兴趣的:(HDU)