Sample input10 12w ........ ww .. WWW ..... WWW .... ww... WW .......... WW .......... W .... W ...... w... w. W ..... WW. w. w. W ..... W .. w. W ...... w... W ....... w. sample output3
Each vertex can be regarded as the same heap as the eight nodes around it.
Algorithm:
1. Traverse each vertex. If it has not been accessed and has water, it goes into the stack and marks it as accessed
2. as long as the stack is not empty, access the neighbor of the top element of the stack in turn. If the neighbor has water and has not been accessed, the neighbor enters the stack. If the neighbor does not have water, the neighbor leaves the stack; if the stack is empty, add 1
# Include <stack> Using Namespace STD; typedef Struct { Int X, Y;} point1; Int Main (){ Int W, h; // Int X, Y; Char C; Int S [101] [101]; stack <point1> sta; scanf (" % D ", & H, & W); getchar (); Int I, J; For (I = 0; I For (J = 0; j <W; j ++) {scanf (" % C ", & C ); If (C = '.') s [I] [J] = 0; Else If (C = 'W') s [I] [J] = 1;} getchar ();} Int Count = 0; Int Num = 0;For (I = 0; I For (J = 0; j <W; j ++) If (S [I] [J] = 1) {point1 P1; p1.x = I; p1.y = J; Sta. push (P1); s [I] [J] = 2; Count = 0; While (! Sta. Empty () {point1 P = Sta. Top (); If (P. x-1)> = 0 & S [p. x-1] [p. y] = 1) {point1 t; T. X = P. x-1; T. y = P. y; Sta. push (t); count ++; P = T; s [T. x] [T. y] = 2 ;} Else If (P. x> = 0 & P. x <H & P. y-1> = 0 & P. Y <W & S [p. x] [p. y-1] = 1) {point1 t; T. X = P. x; T. y = P. y-1; Sta. push (t); count ++; s [p. x] [p. y-1] = 2; P = T ;} Else If (P. X + 1 <H & P. x> = 0 & P. y> = 0 & P. Y <W & S [p. X + 1] [p. y] = 1) {point1 t; T. X = P. X + 1; T. y = P. y; Sta. push (t); count ++; s [p. X + 1] [p. y] = 2; P = T ;} Else If (P. x <H & P. x> = 0 & P. y> = 0 & P. Y + 1 <W & S [p. x] [p. Y + 1] = 1) {point1 t; T. X = P. x; T. y = P. Y + 1; Sta. push (t); count ++; s [p. x] [p. Y + 1] = 2; P = T ;} Else If (P. x-1> = 0 & P. y-1> = 0 & S [p. x-1] [p. y-1] = 1) {point1 t; T. X = P. x-1; T. y = P. y-1; Sta. push (t); count ++; P = T; s [T. x] [T. y] = 2 ;} Else If (P. X + 1 <H & P. Y + 1 <W & S [p. X + 1] [p. Y + 1] = 1) {point1 t; T. X = P. X + 1; T. y = P. Y + 1; Sta. push (t); count ++; P = T; s [T. x] [T. y] = 2 ;}Else If (P. X + 1 <H & P. y-1> = 0 & S [p. X + 1] [p. y-1] = 1) {point1 t; T. X = P. X + 1; T. y = P. y-1; Sta. push (t); count ++; P = T; s [T. x] [T. y] = 2 ;} Else If (P. x-1> = 0 & P. Y + 1 <W & S [p. x-1] [p. Y + 1] = 1) {point1 t; T. X = P. x-1; T. y = P. Y + 1; Sta. push (t); count ++; P = T; s [T. x] [T. y] = 2 ;} Else Sta. Pop ();} num ++;} printf (" % D \ n ", Num ); Return 0 ;}