您的位置:首页 > 其它

ZOJ 1008 (DFS)

2013-09-27 15:41 274 查看
原地址:  点击打开链接

对DFS的恢复现场加深了理解~!

//zoj 1008
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

const int SIZE=6;

int map[SIZE*SIZE][SIZE], cnt[SIZE*SIZE], tot;
int n, m;

int res[SIZE*SIZE];

int check(int top, int right, int bottom, int left)
{
for(int i=0;i<tot;i++)
if(map[i][0]==top && map[i][1]==right && map[i][2]==bottom && map[i][3]==left)
return i;
return -1;
}

bool dfs(int u)
{
if(u==m) return true;

for(int i=0;i<tot;i++)
{
if(cnt[i]==0) continue;
if(u/n!=0 && map[i][0]!=map[res[u-n]][2]) continue;
if(u%n!=0 && map[i][3]!=map[res[u-1]][1]) continue;
res[u]=i;
cnt[i]--;
if(dfs(u+1)) return true;
else cnt[i]++;
}
return false;
}

int main()
{
int top, right, bottom, left;
int line=1;

while(1)
{
cin>>n;
if(n==0) break;
m=n*n;
tot=0;
for(int i=0;i<m;i++)
{
cin>>top>>right>>bottom>>left;
int xh=check(top,right,bottom,left);
if(xh<0)
{
map[tot][0]=top; map[tot][1]=right;
map[tot][2]=bottom; map[tot][3]=left;
cnt[tot++]=1;
}
else cnt[xh]++;
}

if(line>1) printf("\n");
if(dfs(0)) printf("Game %d: Possible\n",line);
else printf("Game %d: Impossible\n",line);
line++;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: