[ Back to the overview Matrix ]

Test case : 8 Queens Problem using Algol 68

Lines used: 26
BEGIN INT n = 8;	# change to solve n-queens problem #
      OP FILL = (REF [] BOOL a) VOID:
	  FOR i FROM LWB a TO UPB a DO a[i] := TRUE OD;
      [n] BOOL column; FILL column;
      [1+1:n+n] BOOL diaga; FILL diaga;
      [1-n:n-1] BOOL diagb; FILL diagb;
      [n] INT position;
      PROC row = (INT q) [] CHAR:
	([2*n] CHAR stars := " *" * n; stars [2*q] := "Q"; stars);

		# "try(k)" -- the first k-1 queens have been placed in the
		  top rows, "column"/"diaga"/"diagb" record which columns
		  and diagonals are still available. #
      PROC try = (INT k) VOID:
	FOR p TO n
	  DO IF k > n
	       THEN print ((row (position[p]), newline))
		    ; (p = n | stop) # remove this line to find all solutions #
	       ELIF column[p] AND diaga[k+p] AND diagb[k-p]
	       THEN column[p] := diaga[k+p] := diagb[k-p] := FALSE;
		    position[k] := p;
		    try (k+1);
		    column[p] := diaga[k+p] := diagb[k-p] := TRUE
	     FI
	  OD;
      try (1)
END
Contributed by andrew.walker at nottingham.ac.uk