|
HP OpenVMS systems documentation |
Previous | Contents | Index |
This appendix contains the source code for the programs used in many
figures of Chapter 8, Chapter 9, and Chapter 10,
EIGHTQUEENS.C AND 8QUEENS.C. These programs are presented here only to
assist in understanding the procedures described in those chapters.
D.1 EIGHTQUEENS.C
Example D-1 contains EIGHTQUEENS.C, the single-module program that solves the eightqueens problem.
Example D-1 Single-Module Program EIGHTQUEENS.C |
---|
extern void setqueen(); extern void removequeen(); extern void trycol(); extern void print(); int a[8]; /* a : array[1..8] of boolean */ int b[16]; /* b : array[2..16] of boolean */ int c[15]; /* c : array[-7..7] of boolean */ int x[8]; /* Solve eight-queens problem */ main() { int i; for (i=0; i <=7; i++) a[i] = 1; for (i=0; i <=15; i++) b[i] = 1; for (i=0; i <=14; i++) c[i] = 1; trycol( 0 ); } /* End main */ void trycol( j ) int j; { int m; int safe; m = -1; while (m++ < 7) { safe = (a[m] ==1) && (b[m + j] == 1) && (c[m - j + 7] ==1); if (safe) { setqueen(m, j); x[j] = m + 1; if (j < 7) trycol(j + 1); else print(); removequeen(m, j); } } } /* End trycol */ void setqueen(m, j) int m; int j; { a[m] = 0; b[m + j] = 0; c[m - j + 7] = 0; } /* End setqueen */ void removequeen(m, j) int m; int j; { a[m] = 1; b[m + j] = 1; c[m - j + 7] = 1; } /* End removequeen */ void print() { int k; for (k=0; k<=7; k++) { printf(" %d", x[k]); } printf("\n"); } /* End print */ |
D.2 8QUEENS.C
8QUEENS.C is the multiple-module program that solves the eightqueens
problem. This program consists of two modules, 8QUEENS.C
(Example D-2) and 8QUEENS_SUB.C (Example D-3).
Example D-2 Main Module 8QUEENS.C |
---|
extern void trycol(); int a[8]; /* a : array[1..8] of boolean */ int b[16]; /* b : array[2..16] of boolean */ int c[15]; /* c : array[-7..7] of boolean */ int x[8]; main() /* Solve eight-queens problem */ { int i; for (i=0; i <=7; i++) a[i] = 1; for (i=0; i <=15; i++) b[i] = 1; for (i=0; i <=14; i++) c[i] = 1; trycol(0); printf(" Solved eight-queens problem!\n"); } /* End main */ |
Example D-3 Submodule 8QUEENS_SUB.C |
---|
extern int a[8]; extern int b[16]; extern int c[15]; extern void setqueen(); extern void removequeen(); extern void print(); int x[8]; void trycol( j ) int j; { int m; int safe; m = -1; while (m++ < 7) { safe = (a[m] ==1) && (b[m + j] == 1) && (c[m - j + 7] ==1); if (safe) { setqueen(m, j); x[j] = m + 1; if (j < 7) trycol(j + 1); else print(); removequeen(m, j); } } } /* End trycol */ void setqueen(m, j) int m; int j; { a[m] = 0; b[m + j] = 0; c[m - j + 7] = 0; } /* End setqueen */ void removequeen(m, j) int m; int j; { a[m] = 1; b[m + j] = 1; c[m - j + 7] = 1; } /* End removequeen */ void print() { int k; for (k=0; k<=7; k++) { printf(" %d", x[k]); } printf("\n"); } /* End print */ |
Index | Contents |