diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..ec5a2f6 Binary files /dev/null and b/.DS_Store differ diff --git a/Puzzles/N-Queens.cpp b/Puzzles/N-Queens.cpp new file mode 100644 index 0000000..ce52310 --- /dev/null +++ b/Puzzles/N-Queens.cpp @@ -0,0 +1,101 @@ +/* +An implementation of the Algorithm solving the N-Queens problem. + +The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 4 Queen problem. +The problem can be solved using backtracking. +**/ +#include +using namespace std; + +bool isSafe(int board[][10],int i,int j,int n){ + // check row and columns + for(int k=0;k=0 && l=0 && l>=0){ + if(board[k][l]){ + return false; + } + k--; + l--; + } + + // If queen is not here then return that + // the location is safe to put the queen + // i.e return true; + return true; + +} + + +bool NQueen(int board[][10],int i,int n){ + // base case + if(i==n){ + // Print the board + for(int k=0;k>n; + // Put n = 4 for testing purposes. + /* + For n=4 this will be the one of the possible outputs: + { 0, 1, 0, 0} + { 0, 0, 0, 1} + { 1, 0, 0, 0} + { 0, 0, 1, 0} + It is to be noted that for a given value of n, there can be + multiple possible configurations. This implementation prints all + possible implementations, separating each by a blank line. + **/ + n = 4; + NQueen(board,0,n); + return 0; +} diff --git a/Puzzles/Tower Of Hanoi.cpp b/Puzzles/Tower Of Hanoi.cpp new file mode 100644 index 0000000..a8eb203 --- /dev/null +++ b/Puzzles/Tower Of Hanoi.cpp @@ -0,0 +1,47 @@ +/** +This code solves the problem of the Tower Of Hanoi. +Here is the problem: +Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: +1) Only one disk can be moved at a time. +2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. +3) No disk may be placed on top of a smaller disk. + +Example problem: +n = 2 disks. +Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'. + +Step 1 : Shift first disk from 'A' to 'B'. +Step 2 : Shift second disk from 'A' to 'C'. +Step 3 : Shift first disk from 'B' to 'C'. + +The pattern here is : +Shift 'n-1' disks from 'A' to 'B'. +Shift last disk from 'A' to 'C'. +Shift 'n-1' disks from 'B' to 'C'. +*/ + +#include +using namespace std; + +void toh(int n,char source,char helper,char dest){ + if(n==0){ + return; + } + + // Recursive solution + toh(n-1,source,dest,helper); + cout<<"Take disk "<>n; + // For a test case, assume n = 2. + n = 2; + toh(n,'A','B','C'); + + return 0; +} \ No newline at end of file