骑士周游

pascal写成的骑士周游,仍有运行时间长(约为10秒左右)的问题,求赐教,以作进一步优化。

uses crt;
const
N=8;

type
chessarray=array [1..N,1..N] of integer;
steparray=array[1..8,1..2] of integer;

var
chess:chessarray;
step:steparray;

procedure init(var _chess:chessarray;var _step:steparray);
var i,j:integer;
begin
        for i:=1 to N do begin
                for j:=1 to N do begin
                        _chess[i][j]:=0;
                end;
        end;

        _step[1][1]:=-2;_step[1][2]:=-1;
        _step[2][1]:=-1;_step[2][2]:=-2;
        _step[3][1]:=1;_step[3][2]:=-2;
        _step[4][1]:=2;_step[4][2]:=-1;

        _step[5][1]:=2;_step[5][2]:=1;
        _step[6][1]:=1;_step[6][2]:=2;
        _step[7][1]:=-1;_step[7][2]:=2;
        _step[8][1]:=-2;_step[8][2]:=1;

end;

procedure print(_chess:chessarray);
var i,j:integer;
begin
        randomize;
        for i:=1 to N do begin
                for j:=1 to N do begin
                        //1-->14
                        textcolor(random(14)+1);
                        write(_chess[i][j]:5);
                end;
                writeln;
        end;
        writeln;
end;

procedure test(_step:steparray);
var i:integer;
begin
        for i:=1 to 8 do begin
        writeln(_step[i][1]:5,_step[i][2]:5);
        end;
end;

function canJump(x,y:integer):boolean;
begin
        if (x>=1) and (x<=N) and (y>=1) and (y<=N) and (chess[x][y]=0)
        then
        begin
        canJump:=true;
        exit;
        end;
        canJump:=false;
end;

procedure backtrack(t,x,y:integer);
var i:integer;
begin
        if t>=N*N then begin
                print(chess);
                readln;
        end
        else
        begin
                for i:=1 to 8 do begin
                    if canJump(x+step[i][1],y+step[i][2])=true
                    then
                    begin
                         x:=x+step[i][1];
                         y:=y+step[i][2];
                         chess[x][y]:=t+1;

                         backtrack(t+1,x,y);

                         chess[x][y]:=0;
                         x:=x-step[i][1];
                         y:=y-step[i][2];
                    end;
                end;
        end;
end;

begin

writeln('waiting...');
writeln;

init(chess,step);
//print(chess);
chess[1][1]:=1;
backtrack(1,1,1);

readln;
end.

图为其中的2组解。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值