連連看
Problem Description “連連看”相信很多人都玩過。沒玩過也沒關係,下面我給大家介紹一下遊戲規則:在一個棋盤中,放了很多的棋子。如果某兩個相同的棋子,可以通過一條線連起來(這條線不能經過其它棋子),而且線的轉折次數不超過兩次,那麼這兩個棋子就可以在棋盤上消去。不好意思,由於我以前沒有玩過連連看,諮詢了同學的意見,連線不能從外面繞過去的,但事實上這是錯的。現在已經釀成大禍,就只能將錯就錯了,連線不能從外圍繞過。
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時,輸入結束。
Output 每一組輸入數據對應一行輸出。如果能消去則輸出"YES",不能則輸出"NO"。 |
菜雞回來看bfs了
#include <bits/stdc++.h>
using namespace std;
int s[1005][1005],n,m;
int vis[1005][1005];
int dir[4][2]= {{0,-1},{1,0},{0,1},{-1,0}};
struct node{
int x,y;
int turn;
int fturn;
};
bool check(int sx,int sy,int ex,int ey) //檢驗點是否合理
{
if(sx<1||sx>n||ex<1||ex>n||sy<1||sy>m||ey<1||ey>m)
return 0;
return 1;
}
bool bfs(int sx,int sy,int ex,int ey)
{
node cur,temp;
memset(vis,1,sizeof(vis));
cur.x = sx,cur.y=sy,cur.fturn=-1,cur.turn = 0;//初始化 -1任何方向,turn轉彎次數
queue <node > load;
load.push(cur);
while(!load.empty())
{
temp = load.front();
if(temp.x==ex&&temp.y==ey&&temp.turn<=2)
return 1;
load.pop();
for(int i=0;i<4;i++)
{
cur = temp;
cur.x=cur.x+dir[i][0];
cur.y=cur.y+dir[i][1];
if( check(cur.x,cur.y,temp.x,temp.y) && (s[cur.x][cur.y]==0)||(cur.x==ex&&cur.y==ey))
{
if(cur.fturn!=-1)
{
if(cur.fturn!=i)
{
cur.fturn = i;
cur.turn ++;
}
}
else cur.fturn = i;
if(cur.turn > 2) continue;
if(cur.turn<=vis[cur.x][cur.y])
{
vis[cur.x][cur.y] = cur.turn;
load.push(cur);
}
}
}
}
return 0;
}
int main()
{
int q;
while(cin>>n>>m)
{
if(n==m&&m==0) break;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>s[i][j];
}
}
cin>>q;
while(q--)
{
int sx,sy,ex,ey;
cin>>sx>>sy>>ex>>ey;
bool flag = check(sx,sy,ex,ey);
/* 預處理 */
if(flag)
{
if(s[sx][sy]==s[ex][ey]&&s[sx][sy]!=0)
printf(bfs(sx,sy,ex,ey)?"YES\n":"NO\n");
else printf("NO\n");
}
else printf("NO\n");
}
}
return 0;
}