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;
}

转载于:https://www.cnblogs.com/mjc467621163/archive/2012/03/18/2404257.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值