TWO SIMPLE ALGORITHMS TO SOLVE N QUEENS PROBLEM
Detail explanations of N queens problem may be found at Wikipedia.
Here I present two programs that solve N queens puzzle.
'NEIGHBOURHOOD' ALGORITHM
The first way uses classical stack technique and neighbourhoods to make search more selective. Neighbourhood here means that when we look for new queen's position we start search near current queen. The figure below shows queens neighbourhood. Queens position is marked with black cross. Neighbourhood positions are filled with green color. Positions with '1' tried first, then positions labelled with '2' and so on.

Such heuristic enhancement increase algorithm performance.
//
// Program.cs - N queen problem solution using 'neighbourhood' heuristic.
// It means that new queen position is selected from
// current queen neighbourhood.
//
// Project:
// Author: S.Zabinskis
//
using System;
using System.Drawing;
using System.Collections.Generic;
namespace Queens1
{
class Program
{
// you may change N
public const int N = 8;
public const int INVALID_MOVE = -1;
public const int INVALID_POSITION = -1;
// used to generate random position for first queen
public static Random rnd = new Random(DateTime.Now.Millisecond + 1000*(DateTime.Now.Second+DateTime.Now.Minute*60));
// list to hold queens
public static List
|
Download source code here.
'ROWS' ALGORITHM
Other way uses obvious fact that for each solution of the problem we have that each chessboard row (or column) contains one and only one queen. So, starting from the first row we have 8 possible positions for the first queen, for second row he have no more that 6 available positions and so on. In case if the next row doesn't have available positions (all cells are under attack) we go back to previous row and move queen to the next available position. The idea of algorithm is illustrated by figure:

Green cells are queens positions. Red cells are for cells under attack (cell label is ordinal number of queen that attacks this field). Blank fields are for available positions.
//
// Program.cs - N queen problem solution using 'rows' approach.
//
// Project:
// Author: S.Zabinskis
//
using System;
using System.Collections.Generic;
namespace Queens4
{
class Program
{
private enum States
{
SavePosition,
NextLine,
Back,
NextColumn
} ;
// you may change N
public const int N = 10;
public const int INVALID_MOVE = -1;
public const int INVALID_POSITION = -1;
public static Random rnd = new Random(DateTime.Now.Millisecond + 1000 * (DateTime.Now.Second + DateTime.Now.Minute * 60));
public static List |
Download source code here.