File: nqueens.c

package info (click to toggle)
hardinfo 0.5.1-1.1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 1,148 kB
  • ctags: 1,212
  • sloc: ansic: 12,199; sh: 199; makefile: 120
file content (37 lines) | stat: -rw-r--r-- 615 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
 * N-Queens Problem Solver
 * Found somewhere on the Internet; can't remember where. Possibly Wikipedia.
 */
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define QUEENS 11

int row[QUEENS];

bool safe(int x, int y)
{
    int i;
    for (i = 1; i <= y; i++)
	if (row[y - i] == x || row[y - i] == x - i || row[y - i] == x + i)
	    return false;
    return true;
}

int nqueens(int y)
{
    int x;
    
    for (x = 0; x < QUEENS; x++) {
	if (safe((row[y - 1] = x), y - 1)) {
	    if (y < QUEENS) {
		nqueens(y + 1);
	    } else {
	        break;
            }
        }
    }
    
    return 0;
}