【HDOJ】2589 正方形划分

暴力DFS

 1 /* 2589 */
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 
 6 #define MAXN 21
 7 
 8 bool map[MAXN][MAXN];
 9 bool visit[MAXN][MAXN];
10 int l, n;
11 
12 bool dfs(int cnt) {
13     int i, j, k;
14     int x, y, r;
15     int ex, ey;
16     bool flag = true;
17 
18     for (x=1; x<=l; ++x) {
19         for (y=1; y<=l; ++y) {
20             if (!visit[x][y]) {
21                 flag = false;
22                 break;
23             }
24         }
25         if (flag == false)
26             break;
27     }
28     if (flag) {
29         if (cnt == 0)
30             return true;
31         else
32             return false;
33     }
34     flag = true;
35     for (r=0; flag&&r<l; ++r) {
36         ex = x + r;
37         ey = y + r;
38         if (ex>l || ey>l)
39             break;
40         k = 0;
41         for (i=x; i<=ex; ++i) {
42             for (j=y; j<=ey; ++j) {
43                 if (map[i][j])
44                     ++k;
45                 if (k>1 || visit[i][j]) {
46                     flag = false;
47                     break;
48                 }
49             }
50             if (flag == false)
51                 break;
52         }
53         if (k==1 && flag) {
54             for (i=x; i<=ex; ++i)
55                 for (j=y; j<=ey; ++j)
56                     visit[i][j] = true;
57             if (dfs(cnt - 1))
58                 return true;
59             for (i=x; i<=ex; ++i)
60                 for (j=y; j<=ey; ++j)
61                     visit[i][j] = false;
62         }
63     }
64     return false;
65 }
66 
67 int main() {
68     int t;
69     int i, j, k;
70     bool flag;
71 
72     #ifndef ONLINE_JUDGE
73         freopen("data.in", "r", stdin);
74     #endif
75 
76     scanf("%d", &t);
77     while (t--) {
78         scanf("%d %d", &l, &n);
79         memset(map, false, sizeof(map));
80         memset(visit, false, sizeof(visit));
81         flag = true;
82         for (i=0; i<n; ++i) {
83             scanf("%d %d", &j, &k);
84             if (map[j][k])
85                 flag = false;
86             map[j][k] = true;
87         }
88         if (flag) {
89             flag = dfs(n);
90         }
91         if (flag)
92             puts("YES");
93         else
94             puts("NO");
95     }
96 
97     return 0;
98 }

 

posted on 2015-03-08 16:47  Bombe  阅读(145)  评论(0编辑  收藏  举报

导航