搜索1009

题目大意:

连连看”相信很多人都玩过。没玩过也没关系,下面我给大家介绍一下游戏规则:在一个棋盘中,放了很多的棋子。如果某两个相同的棋子,可以通过一条线连起来(这条线不能经过其它棋子),而且线的转折次数不超过两次,那么这两个棋子就可以在棋盘上消去。不好意思,由于我以前没有玩过连连看,咨询了同学的意见,连线不能从外面绕过去的,但事实上这是错的。现在已经酿成大祸,就只能将错就错了,连线不能从外围绕过。<br>玩家鼠标先后点击两块棋子,试图将他们消去,然后游戏的后台判断这两个方格能不能消去。现在你的任务就是写这个后台程序。

Input

输入数据有多组。每组数据的第一行有两个正整数n,m(0<n<=1000,0<m<1000),分别表示棋盘的行数与列数。在接下来的n行中,每行有m个非负整数描述棋盘的方格分布。0表示这个位置没有棋子,正整数表示棋子的类型。接下来的一行是一个正整数q(0<q<50),表示下面有q次询问。在接下来的q行里,每行有四个正整数x1,y1,x2,y2,表示询问第x1行y1列的棋子与第x2行y2列的棋子能不能消去。n=0,m=0时,输入结束。<br>注意:询问之间无先后关系,都是针对当前状态的!<br>
Output
每一组输入数据对应一行输出。如果能消去则输出"YES",不能则输出"NO"。
解题思路:bfs
代码:
#include<iostream>  
#include<queue>  
#include<cstring>  
using namespace std;  
struct node  
{  
    int bucket[3];  
    int step;  
};  
bool matrix[101][101][101];  
int bfs(int a,int b,int c)  
{  
    int half,st[3],i,j;;  
    node cur,temp;  
    memset(matrix,0,sizeof(matrix));  
    queue<node>que;  
    st[0]=a,st[1]=b,st[2]=c;  
    half=a>>1;  
    cur.bucket[0]=st[0],cur.bucket[1]=0,cur.bucket[2]=0,cur.step=0;  
    matrix[a][0][0]=1;  
    que.push(cur);  
    while(!que.empty())  
    {  
        cur=que.front(),que.pop();  
        if((cur.bucket[0]==half&&cur.bucket[1]==half)||(cur.bucket[1]==half&&cur.bucket[2]==half)||(cur.bucket[2]==half&&cur.bucket[0]==half))  
        {  
            return cur.step;  
        }  
        cur.step++;  
        for(i=0; i<3; i++)  
        {  
            if(cur.bucket[i]>0)  
                for(j=0; j<3; j++)  
                {  
                    temp=cur;  
                    if(i==j)continue;  
                    if(temp.bucket[i]<=st[j]-temp.bucket[j])  
                    {  
                        temp.bucket[j]+=temp.bucket[i];  
                        temp.bucket[i]=0;  
                    }  
                    else  
                    {  
                        temp.bucket[i]-=st[j]-temp.bucket[j];  
                        temp.bucket[j]=st[j];  
                    }  
                    if(!matrix[temp.bucket[0]][temp.bucket[1]][temp.bucket[2]])  
                    {  
                        matrix[temp.bucket[0]][temp.bucket[1]][temp.bucket[2]]=1;  
                        que.push(temp);  
                    }  
                }  
        }  
    }  
    return 0;  
}  
int main()  
{  
    int a,b,c,ans;  
    while(cin>>a>>b>>c,a||b||c)  
    {  
  
        if(a%2)  
        {  
            cout<<"NO"<<endl;  
            continue;  
        }  
        ans=bfs(a,b,c);  
        if(ans==0)cout<<"NO"<<endl;  
        else cout<<ans<<endl;  
    }  
    return 0;  
}

 

 
posted @ 2016-04-22 19:54  Si考者  阅读(153)  评论(0编辑  收藏  举报