#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 7;
const int M = 8;
int maze[N*M];
int image[N*M],id[N][N];
bool use[M][M],vis[N*M];
int ALL;
void print_ans(){
ALL++;
printf("\n");
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
printf("%4d",image[M*i+j]);
}
printf("\n");
}
}
void dfs(int posi){
if(posi+M<56&&!vis[posi+M]){
int x=maze[posi],y=maze[posi+M];
if(x>y) swap(x,y);
if(!use[x][y]){
use[x][y]=true;
vis[posi]=vis[posi+M]=true;
image[posi]=id[x][y];
image[posi+M]=id[x][y];
for(int i=posi+1;i<56;i++){
if(!vis[i]){
dfs(i); break;
}
if(i==55) print_ans();
}
use[x][y]=false;
vis[posi]=vis[posi+M]=false;
}
}
if((posi+1)%M!=0&&!vis[posi+1]){
int x=maze[posi],y=maze[posi+1];
if(x>y) swap(x,y);
if(!use[x][y]){
use[x][y]=true;
vis[posi]=vis[posi+1]=true;
image[posi]=id[x][y];
image[posi+1]=id[x][y];
for(int i=posi+1;i<56;i++){
if(!vis[i]){
dfs(i); break;
}
if(i==55) print_ans();
}
use[x][y]=false;
vis[posi]=vis[posi+1]=false;
}
}
}
int main()
{
int num=1;
for(int i=0;i<=6;i++)
for(int j=i;j<=6;j++){
//cout<<i<<" "<<j<<" "<<num<<endl;
id[i][j]=num++;
}
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif // ONLINE_JUDGE
memset(vis,false,sizeof(vis));
memset(use,false,sizeof(use));
int kase=1;
while(scanf("%d",&maze[0])==1){
if(kase!=1) printf("\n\n\n");
for(int i=1;i<56;i++) scanf("%d",&maze[i]);
printf("Layout #%d:\n\n",kase);
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
printf("%4d",maze[M*i+j]);
}
printf("\n");
}
ALL=0;
printf("\nMaps resulting from layout #%d are:\n",kase);
dfs(0);
printf("\nThere are %d solution(s) for layout #%d.\n",ALL,kase++);
}
return 0;
}
UVA - 211(网格转化为线性dfs)
最新推荐文章于 2018-11-12 10:57:17 发布