Learn Programming C | C++ | Java | Android | Tips and Tricks

C Progran to Implement N Queen’s Problem using Backtracking

Article Viewed : 1,241 times. 4 Comments

Program : C Progran to Implement N Queen’s Problem using Backtracking

#include<stdio.h>
#include<conio.h>
#include<math.h>
char a[10][10];
int n;
void printmatrix()
{
 int i,j;
 printf("\n");
 for(i=0;i < n;i++)
       {
       for(j=0;j < n;j++)
            printf("%c\t",a[i][j]);
       printf("\n\n");
       }
}
//------------------------------------------
int getmarkedcol(int row)
{
 int i,j;
 for(i=0;i < n;i++)
     if(a[row][i]=='Q')
     {
     return(i);
     break;
     }
}
//------------------------------------------
int feasible(int row, int col)
{
 int i,tcol;
 for(i=0;i < n;i++)
     {
     tcol=getmarkedcol(i);
         if(col==tcol || abs(row-i)==abs(col-tcol))
              return 0;
     }
 return 1;
}
//------------------------------------------
void nqueen(int row)
{
 int i,j;
 if(row < n)
 {
  for(i=0;i < n;i++)
     {
     if(feasible(row,i))
         {
         a[row][i]='Q';
         nqueen(row+1);
         a[row][i]='.';
         }
     }
 }
 else
 {
 printf("\nThe solution is:- ");
 printmatrix();
 }
}
//---------------------------------
void main()
{
 int i,j;
 clrscr();
 printf("\n Enter the no. of queens:- ");
 scanf("%d",&n);
 for(i=0;i < n;i++)
     for(j=0;j < n;j++)
  a[i][j]='.';
 nqueen(0);
 getch();
}

Output :

Enter the no. of queens:- 4
The solution is:-
.       Q       .       .
.       .       .       Q
Q       .       .       .
.       .       Q       .
The solution is:-
.       .       Q       .
Q       .       .       .
.       .       .       Q
.       Q       .       .

About The Author

My name is Pritesh Taral. I am working in well known MNC. as Java Developer. I am part time blogger loves writing articles on C/C++. I am active on facebook using community fan page .One can Visit me @ Facebook Facebook Fan Page

  • Fahad Uddin

    nice blog.
    fahad,
    http://mycsnippets.blogspot.com/

  • Fahad Uddin

    nice.
    Fahad,
    http://mycsnippets.blogspot.com/

  • Aditya

    Invalid code:
    getmarkedcol does not return a value in case the if condition is not true.

    int getmarkedcol(int row)
    {
    int i,j;
    for(i=0;i<n;i++)
    {
    if(a[row][i] =='Q')
    {
    return(i);
    break; // does not have
    //an effect on code
    }

    }
    // no return statement in case if is not true
    //doesnt wrok for the first iteration(row=0)
    }

  • Carter Creekmore

    Pretty! This was a really wonderful post. Thank you for your provided information.