zoj 2412 Farm Irrigation [ dfs ]
题目链接 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1412
大致题意:按照题目给出的几个正方形拼成一个矩形,每个小正方形中间有个管子,问拼成的矩形有多少个能通的管子。
思路:dfs
#include<stdio.h> #include<string.h> #define I (i*3) #define J (j*3) char str[51][51]; int map[159][159]; int n, m; int dir[4][2] = { {0, 1}, {0, -1}, {-1, 0}, {1, 0} }; void dfs(int i, int j) { map[i][j] = 0; for(int k = 0; k < 4; k++) { int x = i + dir[k][0]; int y = j + dir[k][1]; if(x >= 0 && x < 3*n && y >= 0 && y < 3*m && map[x][y]) { dfs(x, y); } } } int main() { while(scanf("%d %d%*c", &n, &m) != EOF) { if(n < 0 || m < 0) break; memset(map, 0, sizeof(map)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { scanf("%c", &str[i][j]); if( str[i][j] == 'A' ) { map[I][J+1] = map[I+1][J] = map[I+1][J+1] = 1; } if( str[i][j] == 'B' ) { map[I+1][J+1] = map[I+1][J+2] = map[I][J+1] = 1; } if( str[i][j] == 'C' ) { map[I+2][J+1] = map[I+1][J] = map[I+1][J+1] = 1; } if( str[i][j] == 'D' ) { map[I+2][J+1] = map[I+1][J+2] = map[I+1][J+1] = 1; } if( str[i][j] == 'E' ) { map[I][J+1] = map[I+2][J+1] = map[I+1][J+1] = 1; } if( str[i][j] == 'F' ) { map[I+1][J+2] = map[I+1][J] = map[I+1][J+1] = 1; } if( str[i][j] == 'G' ) { map[I+1][J+2] = map[I+1][J] = map[I+1][J+1] = map[I][J+1] = 1; } if( str[i][j] == 'H' ) { map[I][J+1] = map[I+2][J+1] = map[I+1][J+1] = map[I+1][J] = 1; } if( str[i][j] == 'I' ) { map[I+1][J+2] = map[I+1][J] = map[I+1][J+1] = map[I+2][J+1] = 1; } if( str[i][j] == 'J' ) { map[I][J+1] = map[I+2][J+1] = map[I+1][J+1] = map[I+1][J+2] = 1; } if( str[i][j] == 'K' ) { map[I][J+1] = map[I+2][J+1] = map[I+1][J+1] = map[I+1][J+2] = map[I+1][J] = 1; } } scanf("%*c"); } /************************** for(int i = 0; i < 3*n; i++) { for(int j = 0; j < 3*m; j++) { printf("%d ", map[i][j]); } printf("\n"); } **************************/ int ans = 0; for(int i = 0; i < 3*n; i++) { for(int j = 0; j < 3*m; j++) { if(map[i][j]) { dfs(i, j); ans++; } } } printf("%d\n", ans); } return 0; }