|
|
1.1 root 1: # QUEENS(6)
2: #
3: # Solutions to n nonattacking queens
4: #
5: # Stephen B. Wampler
6: #
7: # Last modified 8/14/84
8: #
9:
10: global n, solution
11:
12: procedure main(args)
13: local i
14: n := args[1] | 6 # 6 queens by default
15: if not(0 < integer(n)) then stop("parameter must be integer > 0")
16: solution := list(n) # ... and a list of column solutions
17: write(n,"-Queens:")
18: every q(1) # start by placing queen in first col.
19: end
20:
21: # q(c) - place a queen in column c.
22: #
23: procedure q(c)
24: local r
25: static up, down, rows
26: initial {
27: up := list(2*n-1,0)
28: down := list(2*n-1,0)
29: rows := list(n,0)
30: }
31: every 0 = rows[r := 1 to n] = up[n+r-c] = down[r+c-1] &
32: rows[r] <- up[n+r-c] <- down[r+c-1] <- 1 do {
33: solution[c] := r # record placement.
34: if c = n then show()
35: else q(c + 1) # try to place next queen.
36: }
37: end
38:
39: # show the solution on a chess board.
40: #
41: procedure show()
42: static count, line, border
43: initial {
44: count := 0
45: line := repl("| ",n) || "|"
46: border := repl("----",n) || "-"
47: }
48: write("solution: ", count+:=1)
49: write(" ", border)
50: every line[4*(!solution - 1) + 3] <- "Q" do {
51: write(" ", line)
52: write(" ", border)
53: }
54: write()
55: end
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.