/*
* File: KnightsTour.cpp
* ---------------------
* This program find a knight's tour on an N x M chessboard.
*/
#include "KnightsTour.h"
/*
* Function: solveKnightsTour
* Usage: solveKnightsTour(n, m);
* ------------------------------
* Solves the knight's tour problem for a n x m chessboard.
*/
void solveKnightsTour(int n, int m) {
Grid<int> board(n, m);
if (findKnightsTour(board, 0, 0, 1)) {
displayBoard(board);
} else {
cout << "No tour exists for this board." << endl;
}
}
/*
* Function: displayBoard
* Usage: displayBoard(board);
* ---------------------------
* Displays each of the squares in the board along with its sequence
* number in the tour.
*/
void displayBoard(Grid<int> & board) {
for (int i = board.numRows() - 1; i >= 0; i--) {
for (int j = 0; j < board.numCols(); j++) {
cout << " " << setw(2) << board[i][j];
}
cout << endl;
}
}
vector< vector<int> > get_possibilities(Grid<int> & board, int x, int y, int n, int m) {
vector<int> pos_x = {2, 1, -1, -2, -2, -1, 1, 2};
vector<int> pos_y = {1, 2, 2, 1, -1, -2, -2, -1};
vector< vector<int> > possibilities;
for (int i = 0; i < 8; ++i) {
if (x + pos_x[i] >= 0 && x + pos_x[i] <= n && y + pos_y[i] >= 0 && y + pos_y[i] <= m && board[x + pos_x[i]][y + pos_y[i]] == 0) {
possibilities.push_back({x + pos_x[i], y + pos_y[i]});
}
}
return possibilities;
}
bool findKnightsTour(Grid<int> & board, int row, int col, int seq) {
int n = board.numRows() - 1;
int m = board.numCols() - 1;
board[row][col] = seq;
seq = 2;
for (int k = 0; k < (n + 1) * (m + 1) - 1; ++k){
vector< vector<int> > pos = get_possibilities(board, row, col, n, m);
if (pos.size() == 0) return false;
vector<int> minimum = pos[0];
for (unsigned long long i = 0; i < pos.size(); i++) {
int Degree = get_possibilities(board, pos[i][0], pos[i][1], n, m).size();
int MinDegree = get_possibilities(board, minimum[0], minimum[1], n, m).size();
if (Degree <= MinDegree) {
minimum = pos[i];
}
}
row = minimum[0];
col = minimum[1];
board[row][col] = seq;
++seq;
}
return true;
}
Warnsdorff算法(骑士周游问题)
最新推荐文章于 2024-09-04 14:45:59 发布