Commit | Line | Data |
---|---|---|
38ffcb1f SK |
1 | /* A program to solve the 8-queens problem */ |
2 | ||
3 | let | |
4 | var N := 8 | |
5 | ||
6 | type intArray = array of int | |
7 | ||
8 | var row := intArray [ N ] of 0 | |
9 | var col := intArray [ N ] of 0 | |
10 | var diag1 := intArray [N+N-1] of 0 | |
11 | var diag2 := intArray [N+N-1] of 0 | |
12 | ||
13 | function printboard() = ( | |
14 | for i := 0 to N-1 do ( | |
15 | for j := 0 to N-1 do print(if col[i]=j then " O" else " ."); | |
16 | print("\n") | |
17 | ); | |
18 | print("\n") | |
19 | ) | |
20 | ||
21 | function try(c:int) = ( | |
22 | /* for i:= 0 to c do print("."); print("\n"); flush();*/ | |
23 | if c=N | |
24 | then printboard() | |
25 | else | |
26 | for r := 0 to N-1 | |
27 | do | |
28 | if row[r]=0 & diag1[r+c]=0 & diag2[r+7-c]=0 | |
29 | then ( | |
30 | row[r] := 1; | |
31 | diag1[r+c] := 1; | |
32 | diag2[r+7-c] := 1; | |
33 | col[c] := r; | |
34 | try(c+1); | |
35 | row[r] := 0; | |
36 | diag1[r+c] := 0; | |
37 | diag2[r+7-c] := 0 | |
38 | ) | |
39 | ) | |
40 | in | |
41 | try(0) | |
42 | end |