954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

n-queens problem in C

Hello all!
I´m doing the n-queens prolbem in an recursive manner with a twist. The twist i the possibility to chose to place 2-8 queens in a 8x8 board.I have problem with storing the rows properly and print them at the right time inside the recursion,please feel free to give me some tips to proceed.

include <stdio.h>
define TRUE 1
define FALSE 0

int *board;

int main()
{
board=(int*)calloc(8+1,sizeof(int));
board++;
//here goes the userinput no of queens doesn´t matter in this code
int col;
int queens=2;//example from userinput
for(col=1;col<=8;col++)
     placeQueens(1,col,queens);
}
void placeQueens(int row,int col,int queens)
{
       int i;
        for(i=1;i<row;i++)
       {
        if((board[i] == col) || ((row+col)==(i+board[i]))||((row-col)==(i-board[i])))
        {
            check= FALSE;
        }
        else
         check=TRUE;
     }
      if(check==TRUE)
       {
         board[row]=col;
        
        if(row==8)
        {
            
            for(i=1;i<=queens;i++)
            printf("(%d,%d)",i,board[i]);
                    
           printf("\n");
        }            
        else
        {
            for(i=1;i<=8;i++)
            placeQueens(row+1,i);
        }
    }
        
}


this works fine for the first to rows which prints (1,1)(2,3) to (1,8)(2,6) but thats it.The aim is to print the first row first col (1,1) to (8,7) and the (1,2) to (8,8) ie find all solutions with 2 queens on table..

grimbaum
Newbie Poster
2 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

Why use dynamic allocattion to define an 8x8 array? Just define board as int board[8][8] .

Create a function to display the board and just call it.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Thanks, I will do it with this approach..

grimbaum
Newbie Poster
2 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 

if u have correct source of this problem give it me plz

hunter666
Newbie Poster
1 post since Dec 2009
Reputation Points: 6
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You