Enter N,w,h (1<=n<=10,1<=w,h<=n) to find the number of different n-connected blocks in the w*h grid.
Backtracking solution, first determine the search object, lattice connectivity, so the connected block as a search object, each enumeration of a location, and then put a new block, and finally a heavy sentence.
Each block is enumerated many times, and there is a way to ensure that each N-block is enumerated exactly once.
Enumerate each case with the function generate ().
#include <cstdio> #include <cstring> #include <algorithm> #include <set>using namespace std; struct cell{int x, y; Cell (int x=0,int y=0): X (x), Y (y) {}; BOOL operator < (const cell& RHS) Const {return x < rhs.x| | (X==RHS.X&&Y<RHS.Y); }};typedef set<cell> Polyomino; #define For_cell (C,p) for (Polyomino::const_iterator c= (P). Begin (); c!= (P). End () ; ++c) inline Polyomino normalize (const Polyomino &p) {int minx=p.begin ()->x, miny = P.begin ()->y; For_cell (c,p) {MinX = min (MinX, c->x); miny = min (miny, c->y); } Polyomino p2; For_cell (c,p) P2.insert (CELL (c->x-minx,c->y-miny)); return p2;} Inline Polyomino Rotate (const Polyomino &p) {polyomino P2; For_cell (c,p) P2.insert (CELL (c->y,-c->x)); Return normalize (p2);} Inline Polyomino Flip (const polyomino&p) {Polyomino P2; For_cell (c,p) P2.insert (CELL (c->x,-c->y)); Return normalize (p2);} const INT dx[]={-1,1,0,0};const int dy[]={0,0,-1,1};const int maxn=10;set<polyomino> poly[maxn+1];int ans[maxn+1][maxn+1 ][maxn+1];///add a cell to p0 ans check whether it's new if So,add to the Polyonimo setvoid Check_polyomino (const Polyomi no& P0, const cell& c) {Polyomino p = p0; P.insert (c); P=normalize (P); int n=p.size (); for (int i=0;i<4;i++) {if (Poly[n].count (p)!=0) return; P=rotate (P); } p=flip (P); for (int i=0;i<4;i++) {if (Poly[n].count (p)!=0) return; P=rotate (P); } poly[n].insert (P);} void Generate () {Polyomino s; S.insert (Cell (0,0)); Poly[1].insert (s); Generate for (int. n=2;n<=maxn;n++) {for (Set<polyomino>::iterator p=poly[n-1].begin ();p!=poly[n-1].end (); ++p) For_cell (c,*p) for (int dir=0;dir<4;dir++) {CELL News (C->x+dx[dir],c-> ; Y+dy[dir]); if (P->count (News) ==0) Check_polyomino (*p,news); }}///precOmpute answers for (int n=1;n<=maxn;n++) for (int. w=1;w<=maxn;w++) for (int. h=1;h<=maxn;h++) {in T cnt=0; For (Set<polyomino>::iterator p=poly[n].begin ();p!=poly[n].end (); ++p) {int maxx=0,maxy=0; For_cell (c,*p) {Maxx=max (maxx,c->x); Maxy=max (Maxy,c->y); } if (min (maxx,maxy) <min (h,w) &&max (maxx,maxy) <max (h,w)) ++cnt; } ans[n][w][h]=cnt; }}int Main () {Generate (); int n,w,h; while (scanf ("%d%d%d", &n,&w,&h) ==3) {printf ("%d\n", Ans[n][w][h]); } return 0;}
Uva1602-lattice Animals