八数码问题(vijos1620)

算法:搜索

灰常经典的问题啊,话说开始的时候就会写个裸的BFS,这次写加了个HASH,竟然过了。

总之就是移动0,然后四个方向随便乱搞就AC了~

注意要限制一下字符串的长度,否则会MLE的~

program vijos1360;

const
 maxh=3000011;

var
 hashh,dep:array [0..maxh] of longint;
 b:array [0..maxh] of boolean;
 que:array [0..maxh] of string[9];
 head,tail:longint;
 
function hash(x:string):longint;
var
 i,xx:longint;
begin
 val(x,xx);
 i:=xx mod maxh;
 while (hashh[i]<>0) and (hashh[i]<>xx) do
  begin
   inc(i);
   if i>maxh then i:=i mod maxh;
  end;
 if hashh[i]=0 then hashh[i]:=xx;
 exit(i);
end;
 
procedure init;
begin
 head:=0;
 tail:=1;
 readln(que[1]);
 dep[hash(que[1])]:=0;
 b[hash(que[1])]:=true;
end;

procedure BFS;
var
 x,tx:string;
 ch:char;
 t:longint;
begin
 while head<tail do 
  begin
   inc(head);
   x:=que[head];
   t:=pos('0',x);
   
   if t-3>0 then
    begin
     tx:=x;
     ch:=tx[t];
     tx[t]:=tx[t-3];
     tx[t-3]:=ch;
     if not b[hash(tx)] then
      begin
       if tx='123804765' then
        begin
         writeln(dep[hash(x)]+1);
         close(input);
         close(output);
         halt;
        end;
       b[hash(tx)]:=true;
       dep[hash(tx)]:=dep[hash(x)]+1;
       inc(tail);
       que[tail]:=tx;
      end;
    end;
    
   if t mod 3<>1 then
    begin
     tx:=x;
     ch:=tx[t];
     tx[t]:=tx[t-1];
     tx[t-1]:=ch;
     if not b[hash(tx)] then
      begin
       if tx='123804765' then
        begin
         writeln(dep[hash(x)]+1);
         close(input);
         close(output);
         halt;
        end;
       b[hash(tx)]:=true;
       dep[hash(tx)]:=dep[hash(x)]+1;
       inc(tail);
       que[tail]:=tx;
      end;
    end;   
    
   if t mod 3<>0 then
    begin
     tx:=x;
     ch:=tx[t];
     tx[t]:=tx[t+1];
     tx[t+1]:=ch;
     if not b[hash(tx)] then
      begin
       if tx='123804765' then
        begin
         writeln(dep[hash(x)]+1);
         close(input);
         close(output);
         halt;
        end;
       b[hash(tx)]:=true;
       dep[hash(tx)]:=dep[hash(x)]+1;
       inc(tail);
       que[tail]:=tx;
      end;
    end;
    
   if t+3<10 then
    begin
     tx:=x;
     ch:=tx[t];
     tx[t]:=tx[t+3];
     tx[t+3]:=ch;
     if not b[hash(tx)] then
      begin
       if tx='123804765' then
        begin
         writeln(dep[hash(x)]+1);
         close(input);
         close(output);
         halt;
        end;
       b[hash(tx)]:=true;
       dep[hash(tx)]:=dep[hash(x)]+1;
       inc(tail);
       que[tail]:=tx;
      end;
      
    end;             
  end;
end;

begin
 assign(input,'VJ1360.in'); reset(input);
 assign(output,'VJ1360.out'); rewrite(output);
 
 init;
 BFS;
 
 close(input); close(output);
end.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值