1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <iomanip>
#include "knightsTour.h"
using namespace std;
knightsTour::knightsTour(int size)
{
boardSize = size;
for(int i = 0; i < boardSize; i++)
for(int j = 0; j < boardSize; j++)
board[i][j] = 0;
}
void knightsTour::startTour(int x, int y)
{
board[x][y] = 1;
move(x,y);
}
void knightsTour::move(int x, int y)
{
int targetX;
int targetY;
//Move 1 right, 2 down
targetX = x+1;
targetY = y-2;
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 2 right, 1 down
targetX = x+2;
targetY = y-1;
}
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 2 right, 1 up
targetX = x+2;
targetY = y+1;
}
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 1 right, 2 up
targetX = x+1;
targetY = y+2;
}
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 1 left, 2 up
targetX = x-1;
targetY = y+2;
}
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 2 left, 1 up
targetX = x-2;
targetY = y+1;
}
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 2 left, 1 down
targetX = x-2;
targetY = y-1;
}
if (((x >= 0) && (x < boardSize)) || ((y >= 0) && (y < boardSize))){
board[x][y]++;
move(targetX,targetY);
}
else{
//Move 1 left, 2 down
targetX = x-1;
targetY = y-2;
}
}
void knightsTour::print()
{
for(int i = 0; i < boardSize; i++)
{
for(int j = 0; j < boardSize; j++)
cout<<setw(4)<<board[i][j]<<" ";
cout<<endl;
}
cout<<endl<<endl;
}
|