Nadesłany przez Tomasz Lubiński, 25 sierpnia 2008 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
konik - Delphi/Konik.dpr:
//Problem konika (skoczka) szachowego //www.algorytm.org //Adam Mika, Tomasz Lubinski (c) 2008 //Algorytm podaje pierwsze dopuszczalne rozwiązanie problemu dla podanego punktu startowego //pod warunkiem, że takie rozwiązanie istnieje. program Konik; {$APPTYPE CONSOLE} uses SysUtils; const max = 8; //rozmiar problemu - wymiar szachownicy type ArrayOfArray = Array[0..max-1] of Array[0..max-1] of Byte; function ruch(var tab: ArrayOfArray; N: Integer; wariant: Integer; x: Integer; y: Integer; var nx: Integer; var ny: Integer): boolean; begin case (wariant) of 1: begin nx := x+1; ny := y-2; end; 2: begin nx := x+2; ny := y-1; end; 3: begin nx := x+2; ny := y+1; end; 4: begin nx := x+1; ny := y+2; end; 5: begin nx := x-1; ny := y+2; end; 6: begin nx := x-2; ny := y+1; end; 7: begin nx := x-2; ny := y-1; end; 8: begin nx := x-1; ny := y-2; end; end; if ((0<=nx) and (nx<N) and (0<=ny) and (ny<N) and (tab[nx][ny]=0)) then Result := true else Result := false; end; function skoczek(var tab: ArrayOfArray; n: Integer; x: Integer; y: Integer; ktory: Integer): boolean; var nx, ny, w: Integer; begin nx := 0; ny := 0; tab[x,y] := ktory; if (ktory = n*n) then begin Result := true; exit; end else begin for w:=1 to 8 do if(ruch(tab, n, w, x, y, nx, ny) = true) then if (skoczek(tab, n, nx, ny, ktory+1) = true) then begin Result := true; exit; end; tab[x,y] := 0; end; Result := false; end; var tab: ArrayOfArray; i, j: Integer; begin for i:=0 to max-1 do for j:=0 to max-1 do tab[i,j] := 0; if (skoczek(tab, max, 0, 0, 1) = true) then begin for i:=0 to max-1 do begin for j:=0 to max-1 do write(IntToStr(tab[j,i]) + ' '); writeln; end; end; readln; end.