#include "knight.h"
#include <iostream>
bool voyagingKnight(Grid& visited, int x, int y, int m);
using namespace std;
int main() {
Grid visited;
int m =0;
int x = 5;
int y = 5;
voyagingKnight(visited, x, y, m);
return 0;
}
bool voyagingKnight(Grid& visited, int x, int y, int m){
//Ensure that the cell is in bounds.
if (x>=visited.getWidth() || x<0 || y>=visited.getHeight() || y<0){
return false;
}
//Ensure that the cell is untouched.
if(visited[x][y] != -1 && m != 0){
return false;
}
//If the iteration has made it this far then it is a valid move.
visited[x][y] = m;
//If all cells have been touched, output the board and exit the function.
if(m == visited.getWidth() * visited.getHeight() - 1){
//Loop through each row.
for (int i = 0; i < visited.getHeight(); i++){
//Loop through each column
for (int j = 0; j < visited.getWidth(); j++){
//Output each cell.
std::cout << visited[j][i];
//If the value is 1 didget, use 4 spaces, else use only 3.
if (visited[j][i] < 10) std::cout << " ";
else std::cout << " ";
}
//Add a space at the end of every row.
std::cout << "\n";
}
return true;
//Else, the move was valid, but the voyage is not yet complete.
}else{
bool result = false;
//Recursively call each move to check for validity.
result = (result || voyagingKnight(visited, x+2, y+1, m+1));
result = (result || voyagingKnight(visited, x+2, y-1, m+1));
result = (result || voyagingKnight(visited, x-2, y+1, m+1));
result = (result || voyagingKnight(visited, x-2, y-1, m+1));
result = (result || voyagingKnight(visited, x+1, y+2, m+1));
result = (result || voyagingKnight(visited, x+1, y-2, m+1));
result = (result || voyagingKnight(visited, x-1, y+2, m+1));
result = (result || voyagingKnight(visited, x-1, y-2, m+1));
//This position resulted in a voyage.
if( result == true ){
return true;
//Else, not of the moves were sucessfull, so we must backtrack.
}else{
//Unviset the current location.
visited[x][y] = -1;
return false;
}
}
}
getMoves(int i, int j) {
// How do I print out the list of moves?
// Also what should I be returning? A string everytime?
}
我不是在寻找直接的答案,只是关于如何继续的一些指导。我相信我的程序有效,因为它编译并运行没有错误但是我不能完全确定,因为我无法打印出这些动作。关于我的计划的任何其他见解表示赞赏和欢迎。非常感谢提前。