骑士周游

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组解。

骑士周游


版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(骑士周游)