Title Link: http://bailian.openjudge.cn/practice/2815/
#include <iostream> #include <string> #include <cstdio> #include <cstring> #include <queue > #include <map> #include <stack> #include <set> #include <vector> #include <algorithm> #define LL Long longusing namespace Std;int r,c;int rooms[60][60];int color[60][60]; Marker staining, struct room{int r,c;room (int rr=0,int cc=0): R (RR), C (cc) {}};int roomarea=0,maxarea=0,roomnum=0;/*void dfs (int r , int c)//with stack write recursion, can solve the problem of recursive explosion stack, recursion is actually implemented by stack; {stack<room> STK; Stk.push (R,C); while (!stk.empty ()) {rm=stk.top (); R=RM.R,C=RM.C; if (Color[r][c]) stk.pop (); Only the point of access to the mark will he pop, otherwise will WA, because there are four directions to go; else{++roomarea; Color[r][c]=roomnum; if ((rooms[r][c]&1) ==0) Stk.push ((r,c-1)); Go Westward if ((rooms[r][c]&2) ==0) Stk.push (R-1,C); Go North if ((rooms[r][c]&4) ==0) Stk.push (r,c+1); Go eastward if ((rooms[r][c]&8) ==0) Stk.push (R+1,C); Go south}}}*///with recursive solution; void Dfs (int i,int j) {if (color[i][j]) return; ++roomarea; Color[i][j]=roomnum; if ((rooms[i][j]&1) ==0) DFS (I,J-1); Go West if ((rooms[i][j]&2) ==0) DFS (I-1,J); Go North if ((rooms[i][j]&4) ==0) DFS (i,j+1); Go eastward if ((rooms[i][j]&8) ==0) DFS (I+1,J); Go South}int Main () {while (~scanf ("%d%d", &r,&c)) {maxarea=0,roomnum=0; for (int i=1;i<=r;i++) {for (int j=1;j<=c;j++) {scanf ("%d", &rooms[i][j]); }} memset (color,0,sizeof (color)); for (int i=1;i<=r;i++) {for (int j=1;j<=c;j++) {if (!color[i][j]) {++roomn Um, roomarea=0; DFS (I,J); Maxarea=max (Maxarea,roomarea); }}} printf ("%d\n%d\n", Roomnum,maxarea); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
2815: Castle Problem-dfs