DFS+剪枝~
#include<bits/stdc++.h> using namespace std; int a[30][4]; int N; int cnt; int c[30]; int p[30]; unordered_map<long long,int> pos; bool dfs (int v) { if (v==N*N) return true; for (int i=0;i<cnt;i++) { if (c[i]==0) continue; if (v%N!=0&&a[p[v-1]][1]!=a[i][3]) continue; if (v/N!=0&&a[p[v-N]][2]!=a[i][0]) continue; p[v]=i; c[i]--; if (dfs(v+1)) return true; else c[i]++; } return false; } int main () { int T=0; while (scanf("%d",&N)&&N) { pos.clear(); cnt=0; int u,d,l,r,k; for (int i=0;i<N*N;i++) { scanf("%d %d %d %d",&u,&r,&d,&l); for (k=0;k<cnt;k++) { if(u==a[k][0]&&r==a[k][1]&&d==a[k][2]&&l==a[k][3]) break; } if (k==cnt) { cnt++; a[k][0]=u; a[k][1]=r; a[k][2]=d; a[k][3]=l; c[k]=1; } else c[k]++; } if (T!=0) printf("\n"); T++; if (dfs(0)) printf ("Game %d: Possible\n",T); else printf ("Game %d: Impossible\n",T); } return 0; }
原文地址:https://www.cnblogs.com/zhanglichen/p/12311242.html
时间: 2024-10-10 18:00:12