sicily 1153. 马的周游问题[Special judge]

// 与sicily 1152 题意完全一样,但数据量大很多,直接深搜肯定会TLE,需要剪枝
// 可以先搜索扩展性最差的点,这样能有效减少路径数
#include <iostream> // DFS
#include<stdio.h>

#include <algorithm>
using namespace std;
int vis[10][10],path[100],rear,suc;
int mv[8][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};
bool in(int x,int y)
{
return x>=0 && x<8 && y>=0 && y<8;
}
int expand(int x,int y)
{
int cnt=0,newx,newy;
for(int i=0;i<8;++i)
{
newx=x+mv[i][0]; newy=y+mv[i][1];
if(in(newx,newy) && !vis[newx][newy])
cnt++;
}
return cnt;
}
struct node
{
int x,y;
bool operator<(const node& o)const
{
return expand(x,y)<expand(o.x,o.y);
}
}pos[8];
void dfs(int x,int y) //需要剪枝
{

int newx,newy,tail=0;
for(int d=0;d<8;++d)
{
newx=x+mv[d][0];
newy=y+mv[d][1];
if(in(newx,newy) && !vis[newx][newy])
{
pos[tail].x=newx;
pos[tail++].y=newy;
}
}
sort(pos,pos+tail);
for(int i=0;i<tail;++i)
{
newx=pos[i].x;
newy=pos[i].y;
path[rear++]=newx*8+newy+1;
vis[newx][newy]=1;
if(rear==64) //经过所有位置
{

suc=1; //标记成功
return ;

}
dfs(newx,newy);
if(suc)
return ;
vis[newx][newy]=0;
rear--;
}
}
int main()
{
int n;
while(cin>>n&&n!=-1)
{
fill(&vis[0][0],&vis[8][8],0);
int x=(n-1)/8,y=(n-1)%8;
vis[x][y]=1;
rear=0;
path[rear++]=n;
suc=0;
dfs(x,y);
for(int i=0;i<rear;++i)
cout<<path[i]<<" ";
cout<<endl;
}
return 0;
}

posted on 2012-03-18 01:36  sysu_mjc  阅读(306)  评论(0编辑  收藏  举报

导航