Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2022
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. n:=9;;
  2. L:=List([1..n],i->List([1..n],j->0));
  3. pos_max:=0;
  4.  
  5. Backtracking:=function(j)
  6. local i,r,c,s,clash;
  7.  
  8. # Print(L,"\n");
  9.  
  10. for i in [1..n] do
  11. clash := false;
  12.  
  13. # fill in diagonal
  14. for r in [1..n] do
  15. c := ((j+r-2) mod n) + 1;
  16. s := ((i+r-2) mod n) + 1;
  17. L[r][c] := s;
  18.  
  19. # repeated symbol in row
  20. if(ForAny([1..r-1],r2->L[r2][c]=s)) then clash:=true; continue; fi;
  21.  
  22. # repeated symbol in col
  23. if(ForAny([1..c-1],c2->L[r][c2]=s)) then clash:=true; continue; fi;
  24.  
  25. # repeated symbol in antidiagonal
  26. if(ForAny([2..n],k->L[((r-k) mod n) + 1][((c+k-2) mod n) + 1]=s)) then clash:=true; continue; fi;
  27. od;
  28.  
  29. if(clash <> true) then
  30. if(j>pos_max) then
  31. Print("Best thus far: ",L,"\n");
  32. pos_max := j;
  33. fi;
  34.  
  35. if(j=n) then
  36. Print(L,"\n");
  37. else
  38. Backtracking(j+1);
  39. fi;
  40. fi;
  41.  
  42. for r in [1..n] do
  43. c := ((j+r-2) mod n) + 1;
  44. L[r][c] := 0;
  45. od;
  46. od;
  47. end;;
  48.  
  49. Backtracking(1);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement