fork download
  1. const max=10;
  2. type square=array [-1..max+1,-1..max+1] of longint;
  3. vector=array [1..max*max] of longint;
  4. var n:longint;
  5. x:array [1..8] of longint=(-2,-2,-1,-1,+1,+1,+2,+2);
  6. y:array [1..8] of longint=(-1,+1,-2,+2,-2,+2,-1,+1);
  7. c,r:square;
  8. a,b:vector;
  9. checking:boolean;
  10. procedure input;
  11. begin
  12. readln(n);
  13. end;
  14. procedure backTrack(i,u,v:longint);
  15. var j:longint;
  16. begin
  17. if (i>n*n) then
  18. begin
  19. checking:=true;
  20. exit;
  21. end;
  22. for j:=1 to 8 do
  23. begin
  24. if checking then exit;
  25. inc(u,x[j]);
  26. inc(v,y[j]);
  27. if (u>0) and (u<=n) and (v>0) and (v<=n) and (i<=n*n) and (c[u,v]=0) then
  28. begin
  29. c[u,v]:=1;
  30. r[u,v]:=i;
  31. backTrack(i+1,u,v);
  32. c[u,v]:=0;
  33. end;
  34. dec(u,x[j]);
  35. dec(v,y[j]);
  36. end;
  37. end;
  38. procedure solve;
  39. begin
  40. fillchar(c,sizeof(c),0);
  41. c[1,1]:=1;
  42. r[1,1]:=1;
  43. checking:=false;
  44. backTrack(2,1,1);
  45. end;
  46. procedure output;
  47. var j,i:longint;
  48. begin
  49. for j:=1 to n do
  50. begin
  51. for i:=1 to n do write(r[i,j],' ');
  52. writeln;
  53. end;
  54. readln;
  55. end;
  56. begin
  57. input;
  58. solve;
  59. output;
  60. end.
  61.  
Success #stdin #stdout 0s 232KB
stdin
5
stdout
1 6 17 12 23 
18 11 22 7 16 
5 2 13 24 21 
10 19 4 15 8 
3 14 9 20 25