N Queen Problem

This commit is contained in:
AnupKumarPanwar 2017-04-23 13:17:42 +05:30
parent 3aba925011
commit 285a5d626a
3 changed files with 142 additions and 0 deletions

82
Backtracking/N Queens.cpp Normal file
View File

@ -0,0 +1,82 @@
#include<iostream>
#define N 4
using namespace std;
void printSolution(int board[N][N])
{
cout<<"\n";
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
cout<<""<<board[i][j];
cout<<"\n";
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i])
return false;
/* Check upper diagonal on left side */
for (i=row, j=col; i>=0 && j>=0; i--, j--)
if (board[i][j])
return false;
/* Check lower diagonal on left side */
for (i=row, j=col; j>=0 && i<N; i++, j--)
if (board[i][j])
return false;
return true;
}
void solveNQ(int board[N][N], int col)
{
if (col >= N){
printSolution(board);
return;
}
/* Consider this column and try placing
this queen in all rows one by one */
for (int i = 0; i < N; i++)
{
/* Check if queen can be placed on
board[i][col] */
if ( isSafe(board, i, col) )
{
/* Place this queen in board[i][col] */
// cout<<"\n"<<col<<"can place"<<i;
board[i][col] = 1;
/* recur to place rest of the queens */
solveNQ(board, col + 1);
board[i][col] = 0; // BACKTRACK
}
}
}
int main()
{
int board[N][N] = { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
solveNQ(board, 0);
return 0;
}

View File

@ -0,0 +1,60 @@
#include <iostream>
using namespace std;
Multiply(int A[][], int B[][], int n)
{
if (n==2)
{
int p1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]);
int p2= (a[1][0]+a[1][1])*b[0][0];
int p3= a[0][0]*(b[0][1]-b[1][1]);
int p4= a[1][1]*(b[1][0]-b[0][0]);
int p5= (a[0][0]+a[0][1])*b[1][1];
int p6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]);
int p7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]);
int c[n][n];
c[0][0]=p1+p4-p5+p7;
c[0][1]=p3+p5;
c[1][0]=p2+p4;
c[1][1]=p1-p2+p3+p6;
return c[][];
}
else
{
}
}
int main()
{
int p,q,r,s;
cout<<"Enter the dimensions of Matrices";
cin>>n;
int A[n][n],;
int B[n][n],;
cout<<"Enter the elements of Matrix A";
for (int i = 0; i < n; i++)
{
for (int j = 0; j <n ; j++)
{
cin>>A[i][j];
}
}
cout<<"Enter the elements of Matrix B";
for (int i = 0; i < n; i++)
{
for (int j = 0; j <n ; j++)
{
cin>>B[i][j];
}
}
Multiply(A, B, n);
return 0;
}