- fixed comment: bs cannot be NULL anymore (and was never NULL previously)
[libfirm] / ir / be / test / Queens.c
1 /*
2  * Project:     GCC-firm
3  * File name:   test/Queens.c
4  * Purpose:     solve the queens problem
5  * Author:      Markus Armbruster (in sather-k)
6  * Modified by: Michael Beck (for GCC-firm)
7  * Created:     XX.11.2001
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 2001 Universitaet Karlsruhe
10  * Licence:
11  */
12 /*
13   -- The notorious n-queens problem (C.F. Gauss, 1850)
14   -- Copyright (C) 1996 Markus Armbruster
15 */
16
17 #include <stdlib.h>
18 #include <stdio.h>
19
20
21 typedef int boolean;
22
23 #define true    1
24 #define false   0
25
26 static int *row;
27 // queen in column c is at row[c]
28
29 static int myabs(int i) {
30   if(0 > i)
31     i = -i;
32   return(i);
33 }
34
35 static boolean place_ok (int i) {
36   // return whether queen in column i is
37   // not in check from queens left of it
38   int j = 0;
39   boolean res;
40
41   while (j < i) {
42     if ((row[j] == row[i]) || ((myabs(row[i]-row[j])) == (i-j))) {
43       res = false;
44       return(res);
45     }
46     j = j+1;
47   }
48   res = true;
49   return(res);
50 }
51
52 static int solve (int n) {
53   // return the number of solutions to the n-queens problem
54   int c = 0;
55   int res = 0;
56
57   row = (void *)malloc(sizeof(*row) * n);
58   row[0] = -1;
59   while (c >= 0) {
60     row[c] = row[c]+1;
61     while ((row[c] < n) && (!place_ok(c))) {
62       row[c] = row[c]+1;
63     }
64     if (row[c] < n) { // successfully placed at (c,row[c])
65       if (c == n-1)
66         res = res+1;
67       else {
68         c = c+1;
69         row[c] = -1;
70       }
71     }
72     else // dead end, track back
73       c = c-1;
74   }
75   free(row);
76
77   return(res);
78 }
79
80 static void usage (const char *progname) {
81   printf("usage: %s [n]\n", progname);
82 }
83
84
85 int main (int argc, char *argv[]) {
86   int n;
87
88   switch (argc) {
89   case 1:
90     n = 8;
91     break;
92   case 2:
93     n = atoi(argv[1]);
94     break;
95   default:
96     usage("queens");
97     return 0;
98   }
99   printf("The %d-queens problem has %d solutions.\n", n, solve(n));
100
101   return 0;
102 }