ZOJ 2412 Farm Irrigation

农田需要灌溉,农田分为好多小块,每一块都有他的固定管道。可以与周围的管道相通。

 

类似于floodfill,就是管道相通的几块农田可以用一个水源,求最少需要多少水源才能使所有的农田得到灌溉。

 

#include<stdio.h> #include<stdlib.h> #include<string.h> int n,m; struct node { int is; int up,down,left,right; }e,t,mat[51][51]; struct node change(char c) //把字符转换为各种地图的情况 { struct node t; t.left=t.right=t.up=t.down=0; if( c == 'A' ) {t.left=t.up=1;return t;} if( c == 'B' ) {t.right=t.up=1;return t;} if( c == 'C' ) {t.left=t.down=1;return t;} if( c == 'D' ) {t.right=t.down=1;return t;} if( c == 'E' ) {t.down=t.up=1;return t;} if( c == 'F' ) {t.left=t.right=1;return t;} if( c == 'G' ) {t.left=t.up=t.right=1;return t;} if( c == 'H' ) {t.left=t.up=t.down=1;return t;} if( c == 'I' ) {t.left=t.down=t.right=1;return t;} if( c == 'J' ) {t.right=t.down=t.up=1;return t;} if( c == 'K' ) {t.left=t.right=t.up=t.down=1;return t;} return t; } void dfs( int x,int y ) //dfs过程,就是把连接着的周围农田标记成已经得到灌溉 { if( mat[x][y].up && !mat[x-1][y].is && mat[x-1][y].down ) mat[x-1][y].is=1,dfs(x-1,y); if( mat[x][y].down && !mat[x+1][y].is && mat[x+1][y].up ) mat[x+1][y].is=1,dfs(x+1,y); if( mat[x][y].left && !mat[x][y-1].is && mat[x][y-1].right ) mat[x][y-1].is=1,dfs(x,y-1); if( mat[x][y].right &&!mat[x][y+1].is && mat[x][y+1].left ) mat[x][y+1].is=1,dfs(x,y+1); } int main(void) { int i,j,count; char c; while( scanf("%d%d",&n,&m) != EOF ) { getchar(); if( n < 0 && m <0 ) break; for( i = 1; i <= n; i++ ){ for( j = 1; j <= m; j++ ) { c = getchar(); mat[i][j] = change(c); mat[i][j].is = 0; } getchar(); } for( i = 1; i <= n; i++ ) mat[i][1].left = mat[i][m].right = 0; for( i = 1; i <= m; i++ ) mat[1][i].up = mat[n][i].down = 0; count = 0; for( i = 1; i <= n; i++ ) for( j = 1; j <= m; j++ ) if( mat[i][j].is == 0 ) mat[i][j].is = 1,dfs(i,j),count++; printf("%d/n",count); } return 0; }  

你可能感兴趣的:(ZOJ 2412 Farm Irrigation)