sicily 1152. 简单的马周游问题[Special judge]

#include <iostream>        // DFS
#include<stdio.h>

#include <cstring>
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}};
void dfs(int x,int y)
{
int newx,newy;
for(int d=0;d<8;++d)
{
newx=x+mv[d][0]; newy=y+mv[d][1];
if( newx>=0 && newx<5 && newy>=0 && newy<6 && !vis[newx][newy] )
{
path[rear++]=newx*6+newy+1;
vis[newx][newy]=1;
if(rear==30) //经过所有位置
{

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[5][6],0);
int x=(n-1)/6,y=(n-1)%6;
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:16  sysu_mjc  阅读(260)  评论(0编辑  收藏  举报

导航