wikioi1004 四子连棋

题目描述 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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值