用Pascal解决中国象棋的跳马——回溯算法

这里将所有条件和最优条件输出

program chess;
const xx:array[1..4] of 1..2=(1,2,2,1);
      yy:array[1..4] of -2..2=(2,1,-1,-2);
var
  t,tt,t1,tt1:array[0..10] of integer;
  i,p,q,num,m:integer;
procedure priteln(x1:integer;y1:integer);
begin
  i:=1;
  write('(0,0)');
  repeat
    write('--','(',t[i],',',tt[i],')');
    inc(i);
  until (t[i]=x1)and(tt[i]=y1);
   write('--','(',t[i],',',tt[i],')');
   writeln;
end;
procedure findway(k:integer);
var
  x,y,n:integer;
begin
  for n:=1 to 4 do begin
    x:=t[k-1]+xx[n];
    y:=tt[k-1]+yy[n];
    if not((x>p)or(y<0)or(y>4)) then begin
      t[k]:=x;
      tt[k]:=y;
      if(x=p) and (y=q) then begin
      if(m>k) then begin
      m:=k;
      tt1:=tt;
      t1:=t;
      end;
      priteln(p,q);
      inc(num);
      end;
      findway(k+1);
    end;
  end;
end;
begin
  num:=0;
  m:=100;
  readln(p,q);
  findway(1);
  writeln('This is the best way how to finsh it:');
  write('(0,0)');
  for i:=1 to m do begin
    write('--','(',t1[i],',',tt1[i],')');
  end;
  readln;
end.

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/G1342522389/article/details/50465344
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞