Square Division [dfs], square dfs
Problem Description a square with a side length of L can be divided into L * L small squares. there are N stones in N small squares. Can we divide them into N squares so that each square has exactly one stone and the N squares exactly constitute the whole square.
Input data first contains an integer T, indicating the number of test instances, followed by T group data. The first row of each group contains two integers, L, N, next, there are two integers (r and c) in each row in N rows, indicating that there is a stone in the small square in Column c of row r. 1 <L <= 20; 1 <N <= L * L; 1 <= r, c <= L.
Output for each test instance, if it can be divided into N squares, YES is Output; otherwise NO is Output.
Sample Input
35 82 43 33 43 54 24 44 55 53 21 13 32 41 11 22 12 2
Sample Output
YESNOYES
Solution: traverse from the upper left corner. If a stone exists, traverse down and mark the area to be scanned. If not found, recursively roll back until it jumps out.
# Include <cstdio> # include <cstring> int L, N, a [22] [22], vis [22] [22], xx, yy; int js (int x, int y, int len) {// Number of stones int cnt = 0; for (int I = 0; I <len; I ++) for (int j = 0; j <len; j ++) if (a [x + I] [y + j]) cnt ++; return cnt ;} void mark (int x, int y, int len, int k) {// mark for (int I = 0; I <len; I ++) for (int j = 0; j <len; j ++) vis [x + I] [y + j] = k;} void getNext () {// obtain the next vertex for (int I = 1; I <= L; I + +) For (int j = 1; j <= L; j ++) if (vis [I] [j] = false) {xx = I; yy = j; return ;}} int my_find (int x, int y, int n) {int len, cnt; for (len = 1; x + len <= L + 1 & y + len <= L + 1; len ++) {cnt = js (x, y, len ); if (cnt = 0) continue; else if (cnt> 1) return 0; mark (x, y, len, 1); n-= len * len; if (! N) return 1; getNext (); if (my_find (xx, yy, n) return 1; else {// recursive restoration field mark (x, y, len, 0); n + = len * len;} return 0;} int main () {int T, r, c; scanf ("% d", & T ); while (T --) {memset (a, 0, sizeof (a); memset (vis, 0, sizeof (vis); scanf ("% d ", & L, & N); for (int I = 1; I <= N; I ++) {scanf ("% d", & r, & c ); a [r] [c] = 1;} if (my_find (1, 1, L * L) printf ("YES \ n "); else printf ("NO \ n");} return 0 ;}