In: Computer Science
Working code implemented in C++ and appropriate comments provided for better understanding.
Here I am attaching code for all files:
main.cpp:
#include <iostream>
#include <fstream>
#include "nQueenPuzzle.h"
int main() {
int max = 10;
std::ofstream output;
output.open("output.txt");
for (int i = 0; i < max; i++) {
nQueensPuzzle queens(i + 1);
output << "\t\tBOARD " << i + 1 << "x" << i + 1 << "\n\n";
queens.queensConfiguration(0, output);
std::cout << "A " <<
i + 1 << "x" << i + 1 << " board has ";
std::cout <<
queens.solutionsCount();
std::cout << "
solutions.\n";
output << "\nA " <<
i + 1 << "x" << i + 1 << " board has ";
output <<
queens.solutionsCount();
output << "
solutions.\n\n";
}
std::cout << "Output has been saved to output.txt because large numbers output too many lines.\n";
output.close();
return 0;
}
nQueenPuzzle.cpp:
#include <iostream>
#include <fstream>
#include <cmath>
#include "nQueenPuzzle.h"
nQueensPuzzle::nQueensPuzzle(int queens) {
noOfQueens = queens;
queensInRow = new int[noOfQueens];
noOfSolutions = 0;
}
bool nQueensPuzzle::canPlaceQueen(int k, int i) {
for (int j = 0; j < k; j++) {
if ((queensInRow[j] == i) ||
(abs(queensInRow[j] - i) == abs(j-k))) {
return
false;
}
}
return true;
}
void nQueensPuzzle::queensConfiguration(int k, std::ofstream
&output) {
for (int i = 0; i < noOfQueens; i++) {
if (canPlaceQueen(k, i)) {
queensInRow[k] =
i;
if (k ==
noOfQueens - 1) {
printConfiguration(output);
} else {
queensConfiguration(k + 1, output);
}
}
}
}
void nQueensPuzzle::printConfiguration(std::ofstream
&output) {
noOfSolutions++;
output << "(";
for (int i = 0; i < noOfQueens - 1; i++) {
output << queensInRow[i]
<< ", ";
}
output << queensInRow[noOfQueens - 1]
<< ")\n";
}
int nQueensPuzzle::solutionsCount() {
return noOfSolutions;
}
nQueensPuzzle.h:
#include <fstream>
class nQueensPuzzle {
public:
nQueensPuzzle(int queens = 8);
bool canPlaceQueen(int k, int i);
void queensConfiguration(int k, std::ofstream
&output);
void printConfiguration(std::ofstream
&output);
int solutionsCount();
private:
int noOfSolutions;
int noOfQueens;
int *queensInRow;
};
Sample Output Screenshots: