题目描述 Description
在一个4*4的棋盘上摆放了14颗棋子,其中有7颗白色棋子,7颗黑色棋子,有两个空白地带,任何一颗黑白棋子都可以向上下左右四个方向移动到相邻的空格,这叫行棋一步,黑白双方交替走棋,任意一方可以先走,如果某个时刻使得任意一种颜色的棋子形成四个一线(包括斜线),这样的状态为目标棋局。
● | ○ | ● | |
○ | ● | ○ | ● |
● | ○ | ● | ○ |
○ | ● | ○ |
输入描述 Input Description
从文件中读入一个4*4的初始棋局,黑棋子用B表示,白棋子用W表示,空格地带用O表示。
输出描述 Output Description
用最少的步数移动到目标棋局的步数。
样例输入 Sample Input
BWBO
WBWB
BWBW
WBWO
样例输出 Sample Output
5
题解:还是爆搜,本题应该用广搜比较好,我写的程序是深搜
const
dx:array[1..4,1..2]of shortint=((1,0),(0,1),(0,-1),(-1,0));
var
a:array[1..4,1..4]of char;
i,j:shortint;
ans,n:longint;
function check:boolean;
var
i:shortint;
begin
for i:=1 to 4 do
begin
if(a[i,1]=a[i,2])and(a[i,1]=a[i,3])and(a[i,1]=a[i,4])then exit(true);
if(a[1,i]=a[2,i])and(a[1,i]=a[3,i])and(a[1,i]=a[4,i])then exit(true);
end;
if(a[1,1]=a[2,2])and(a[1,1]=a[3,3])and(a[1,1]=a[4,4])then exit(true);
if(a[4,1]=a[3,2])and(a[4,1]=a[2,3])and(a[4,1]=a[1,4])then exit(true);
exit(false);
end;
procedure dfs(step,dir,x1,y1:integer;last:char);
var
i,j,k,x,y:shortint;
begin
if step>=ans then exit;
if check then ans:=step
else
begin
if step<>0 then
begin
a[x1,y1]:=last;
a[x1+dx[dir,1],y1+dx[dir,2]]:='O';
end;
for i:=1 to 4 do
for j:=1 to 4 do
if a[i,j]='O'then
for k:=1 to 4 do
begin
x:=i+dx[k,1];
y:=j+dx[k,2];
if(x<5)and(x>0)and(y<5)and(y>0)and(a[x,y]<>last) then
dfs(step+1,k,i,j,a[x,y]);
end;
if step<>0 then
begin
a[x1,y1]:='O';
a[x1+dx[dir,1],y1+dx[dir,2]]:=last;
end;
end;
end;
begin
for i:=1 to 4 do
begin
for j:=1 to 4 do
read(a[i,j]);
readln;
end;
ans:=100;
dfs(0,0,0,0,'0');
writeln(ans-1);
end.