您的位置:首页 > 其它

HDU1401 BFS

2013-02-14 21:36 211 查看
题意:有上一状态到下一状态

单向bfs

就是每次只改变一个点的一个方向!!!

( 参考。。。http://blog.csdn.net/cscj2010/article/details/7371482)

View Code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 8;
bool vis[ maxn ][ maxn ][ maxn ][ maxn ][ maxn ][ maxn ][ maxn ][ maxn ];
bool mat[ maxn+1 ][ maxn+1 ];
struct node{
int x,y;
}a[ maxn ];
struct node2{
int x[4],y[4],t;
}p,pp;
void init(){
memset( mat,false,sizeof( mat ));
}
const int dx[]={0,0,1,-1};
const int dy[]={1,-1,0,0};

bool ok( node2 p ){
for( int i=0;i<4;i++ ){
if( mat[ p.x[i] ][ p.y[i] ]==false )
return false;
}
return true;
}

bool empty( node2 pp,int i ){
for( int k=0;k<4;k++ ){
if( i!=k ){
if( pp.x[i]==pp.x[k]&&pp.y[i]==pp.y[k] ){
return false;
}
}
}
return true;
}

int bfs(){
for( int i=0;i<4;i++ ){
p.x[i]=a[i].x;
p.y[i]=a[i].y;
//    p.t=0;
}
p.t=0;
if( ok(p)==true )
return p.t;
queue<node2>q;
q.push( p );
memset( vis,false,sizeof( vis ));
vis[ p.x[0] ][ p.y[0] ][ p.x[1] ][ p.y[1] ][ p.x[2] ][ p.y[2] ][ p.x[3] ][ p.y[3] ]=true;
while( !q.empty() ){
p=q.front(),q.pop();
if( p.t>=8 )
return -11;
if( ok(p)==true )
return p.t;
for( int i=0;i<4;i++ ){
for( int j=0;j<4;j++ ){//dir
pp=p;
pp.x[ i ]=p.x[ i ]+dx[ j ];
pp.y[ i ]=p.y[ i ]+dy[ j ];
pp.t=p.t+1;
if( pp.x[0]<0||pp.x[0]>=8||pp.y[0]<0||pp.y[0]>=8||pp.x[1]<0||pp.x[1]>=8||pp.y[1]<0||pp.y[1]>=8 )
continue;
if( pp.x[2]<0||pp.x[2]>=8||pp.y[2]<0||pp.y[2]>=8||pp.x[3]<0||pp.x[3]>=8||pp.y[3]<0||pp.y[3]>=8 )
continue;
if( vis[ pp.x[0] ][ pp.y[0] ][ pp.x[1] ][ pp.y[1] ][ pp.x[2] ][ pp.y[2] ][ pp.x[3] ][ pp.y[3] ]==true )
continue;
if( empty( pp,i )==true ){
vis[ pp.x[0] ][ pp.y[0] ][ pp.x[1] ][ pp.y[1] ][ pp.x[2] ][ pp.y[2] ][ pp.x[3] ][ pp.y[3] ]=true;
if( ok(pp)==true )
return pp.t;
q.push( pp );
}
else{
pp.x[i]+=dx[j];
pp.y[i]+=dy[j];
if( pp.x[0]>=0&&pp.x[0]<8&&pp.y[0]>=0&&pp.y[0]<8&&pp.x[1]>=0&&pp.x[1]<8&&pp.y[1]>=0&&pp.y[1]<8&&pp.x[2]>=0&&pp.x[2]<8&&pp.y[2]>=0&&pp.y[2]<8&&pp.x[3]>=0&&pp.x[3]<8&&pp.y[3]>=0&&pp.y[3]<8  ){
if( empty( pp,i )==true&&vis[ pp.x[0] ][ pp.y[0] ][ pp.x[1] ][ pp.y[1] ][ pp.x[2] ][ pp.y[2] ][ pp.x[3] ][ pp.y[3] ]==false ){
vis[ pp.x[0] ][ pp.y[0] ][ pp.x[1] ][ pp.y[1] ][ pp.x[2] ][ pp.y[2] ][ pp.x[3] ][ pp.y[3] ]=true;
if( ok(pp)==true )
return pp.t;
q.push( pp );
}
}
}
}
}
}
return -11;
}

int main(){
while( scanf("%d%d",&a[0].x,&a[0].y)==2 ){
a[0].x--,a[0].y--;
for( int i=1;i<4;i++ ){
scanf("%d%d",&a[i].x,&a[i].y);
a[i].x--,a[i].y--;
}
init();
int x,y;
for( int i=0;i<4;i++ ){
scanf("%d%d",&x,&y);
x--,y--;
mat[x][y]=true;
}
int flag=bfs( );
if( flag!=-11 )
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: