在一個4*4的棋盤上擺放了14顆棋子,其中有7顆白色棋子,7顆黑色棋子,有兩個空白地帶,任何一顆黑白棋子都可以向上下左右四個方向移動到相鄰的空格,這叫行棋一步,黑白雙方交替走棋,任意一方可以先走,如果某個時刻使得任意一種顏色的棋子形成四個一線(包括斜線),這樣的狀態爲目標棋局。
● | ○ | ● | |
○ | ● | ○ | ● |
● | ○ | ● | ○ |
○ | ● | ○ |
從文件中讀入一個4*4的初始棋局,黑棋子用B表示,白棋子用W表示,空格地帶用O表示。
用最少的步數移動到目標棋局的步數。
BWBO
WBWB
BWBW
WBWO
5
題目就是這樣了。
是不是感覺。。。
()*……%#¥%#¥@%#()*&()*
反正我是這麼想的,思路如下:
%#!#!%¥*……&¥!&#&……*()……¥*¥*)}{}:》}》《》《》+)&)……*……#%¥&())()……¥6&&(**854764$(&^78*%**O(*4)*(^7*#73&FGY948&&*0986*&¥……&%
嗯,大概就是這樣。。
作爲一個蒟蒻,這可是我第一個上百行的代碼呢
代碼如下()&¥%……:
#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y,p,q,last,step,map[5][5];
};
queue<node> que;
node st;
int a[4],cnt,dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
const int mod=985321;
bool m[985322];
bool check(node now)
{
int k=0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
{
k=(k*3+now.map[i][j])%mod;
}
k=(k*3+now.last)%mod;
if(!m[k])
{
m[k]=true;
return false;
}
else return true;
}
bool line_up(node now)
{
if(now.map[0][0]==now.map[1][1]&&now.map[2][2]==now.map[1][1]&&now.map[2][2]==now.map[3][3])return true;
if(now.map[0][3]==now.map[1][2]&&now.map[1][2]==now.map[2][1]&&now.map[3][0]==now.map[2][1])return true;
for(int i=0;i<4;i++)
{
if(now.map[i][0]==now.map[i][1]&&now.map[i][2]==now.map[i][1]&&now.map[i][3]==now.map[i][2])return true;
if(now.map[0][i]==now.map[1][i]&&now.map[2][i]==now.map[1][i]&&now.map[3][i]==now.map[2][i])return true;
}
return false;
}
bool condition1(node now)
{
if(now.x>=0&&now.x<4)
if(now.y>=0&&now.y<4)
if(now.last!=now.map[now.x][now.y])
if(now.map[now.x][now.y]!=0)
return true;
return false;
}
bool condition2(node now)
{
if(now.p>=0&&now.p<4)
if(now.q>=0&&now.q<4)
if(now.last!=now.map[now.p][now.q])
if(now.map[now.p][now.q]!=0)
return true;
return false;
}
int bfs(int x,int y,int p,int q,int last)
{
st.x=x;st.y=y;st.p=p;st.q=q;st.last=0;
que.push(st);
while(!que.empty())
{
node curr=que.front();que.pop();
for(int i=0;i<4;i++)
{
node next=curr;
next.x+=dx[i];
next.y+=dy[i];
next.step++;
if(condition1(next))
{
swap(next.map[next.x][next.y],next.map[curr.x][curr.y]);
next.last=next.map[curr.x][curr.y];
if(!check(next)){
if(line_up(next))return next.step;
que.push(next);
}
swap(next.map[next.x][next.y],next.map[curr.x][curr.y]);
next.last=curr.last;
}
next.x-=dx[i];
next.y-=dy[i];
next.p+=dx[i];
next.q+=dy[i];
if(condition2(next))
{
swap(next.map[next.p][next.q],next.map[curr.p][curr.q]);
next.last=next.map[curr.p][curr.q];
if(!check(next)){
if(line_up(next))return next.step;
que.push(next);
}
swap(next.map[next.p][next.q],next.map[curr.p][curr.q]);
next.last=curr.last;
}
}
}
}
int main()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
char c;cin>>c;
if(c=='B')st.map[i][j]=1;
else if(c=='W')st.map[i][j]=2;
else
{
st.map[i][j]=0;
a[cnt++]=i;
a[cnt++]=j;
}
}
getchar();
}
cout<<bfs(a[0],a[1],a[2],a[3],0);
return 0;
}
其實想一想,是真的難呢
以後誰和我提到“四子連棋”,我跟誰急哈哈哈哈(@&()&%()979^5)%¥&*!2&)?!。。
by hah