Program to solve eight queens problem using backtracking technique

//program to solve eightqueens problem using backtracking technique


#include <iostream.h>
#include<conio.h>

class eightqueen
{
	private:
		int row[8],s;
		int safe(int,int);
		void putboard();

	public:
		eightqueen()
		{
			s=0;
		}
		void queen(int);
};

int eightqueen::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 0;
	return 1;
}

void eightqueen::putboard()
{
	int x,y;
	cout<<"\nSolution #"<<++s<<":\n---------------------------------\n";
	for(y=0;y<8; y++)
	{
		for (x=0;x<8;x++)
			if(x==row[y])
				cout<<"| Q ";
			else
				cout<<"|   ";
		cout<<"|\n---------------------------------\n";
	}
	getch();
}

void eightqueen::queen(int y)
{
	int x;
	for(x=0;x<8;x++)
	{
		row[y-1]=x;

		if( safe(x,y-1) )
			if (y<8)
				queen(y+1);
			else
				putboard();
	}
}

void main()
{
	eightqueen eq;
	clrscr();

	eq.queen(1);
}
Chitra
Chitra

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in