Description:
There are 11 different kinds of water pipes in A-K, each pipe connection direction is different. A m × n Field Water Pipe chart is provided to find the minimum number of outlets required for irrigation of all the fields. Original question zju2412
Analysis:
A rough look, this question can be usedSearch Algorithm. This is to find the total number of connected components.
An Efficient Method to Evaluate the number of connected components of a graph is to useQuery set. This question can also be solved using the query set.
For each grid in the map, determine whether the water pipe can be connected to the grid above and on the left. If yes, they are all in one.
Finally, count and check the number of connected branches in the set.
Code: 0.00 s
/*
Zju2412 Farm Irrigation
*/
# Include <stdio. h>
# Define n 51
# Define ID (I, j) (I * m + J + 1)
Int dir [] [2] = {-1}, {0,-1}; // up down
Int link [] [4] = {,}, {,} // A B
, {,}, {,} // C d
, {,}, {,} // E F
, {,}, {,} // G H
, {0, 1, 1}, {1, 1} // I J
, {,}; // K
Int f [N * N], m, n;
Char map [N] [N], ch;
Int x, y, u, v, p, q, t;
Int connect (int u, int v, int e ){
If (! E) {// up down
If (link [u] [0] & link [v] [3]) return 1;
Else return 0;
}
Else {// left right
If (link [u] [2] & link [v] [1]) return 1;
Else return 0;
}
}
Int root (INT p ){
Q = P;
While (F [Q]) q = f [Q];
While (F [p]) {
T = f [p];
F [p] = Q;
P = T;
}
Return Q;
}
Void work (int I, Int J, int e ){
X = I + dir [E] [0];
Y = J + dir [E] [1];
U = map [I] [J];
V = map [x] [Y];
If (connect (U, V, E )){
P = root (ID (I, j ));
Q = root (ID (x, y ));
If (P! = Q) f [p] = Q;
}
}
Int main ()
{
Int I, J, K, ans;
While (scanf ("% d", & N, & M), M! =-1 | n! =-1)
{
// Input
Getchar ();
For (I = 0; I <n; I ++ ){
For (j = 0; j <m; j ++ ){
Scanf ("% C", & Ch );
Map [I] [J] = CH-'A ';
}
Getchar ();
}
// Init
For (I = 0; I <= N * m; I ++) f [I] = 0;
// Work
For (I = 0; I <n; I ++ ){
For (j = 0; j <m; j ++ ){
If (I) work (I, j, 0); // up
If (j) work (I, j, 1); // left
}
}
// Count
Ans = 0;
For (I = 0; I <n; I ++)
For (j = 0; j <m; j ++ ){
K = ID (I, j );
If (root (K) = k) ans ++;
}
// Output
Printf ("% d/N", ANS );
}
Return 0;
}