#include<iostream> #include<array> using namespace std; const int N = 8, STEPS = N*N-1; int border[N][N]; bool move(int currentRow, int currentColumn, int steps) { if (currentRow<0 || currentRow > N - 1 || currentColumn<0 || currentColumn > N - 1) return false; if (steps == -1) return true; if (border[currentRow][currentColumn] != 0) return false; steps--; border[currentRow][currentColumn] = STEPS - steps; if (move(currentRow + 1, currentColumn + 2, steps) == true)return true; if (move(currentRow + 1, currentColumn - 2, steps) == true)return true; if (move(currentRow - 1, currentColumn + 2, steps) == true)return true; if (move(currentRow - 1, currentColumn - 2, steps) == true)return true; if (move(currentRow + 2, currentColumn + 1, steps) == true)return true; if (move(currentRow + 2, currentColumn - 1, steps) == true)return true; if (move(currentRow - 2, currentColumn + 1, steps) == true)return true; if (move(currentRow - 2, currentColumn - 1, steps) == true)return true; border[currentRow][currentColumn] = 0; return false; } int main() { int CurrentRow = 0, CurrentColumn = 0; for(CurrentRow=0;CurrentRow < N;CurrentRow++) for (CurrentColumn = 0; CurrentColumn < N; CurrentColumn++) { cout << "start from " << CurrentRow << " " << CurrentColumn << "\n"; if (move(CurrentRow, CurrentColumn, STEPS) == true) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout.fill('0'); cout.width(2); cout << border[i][j] << " "; } cout << endl; } } else { cout << "No path found!" << endl; } } }
编写程序求解骑士巡游问题:在n行n列的棋盘上(如n=5),假设一位骑士(按象棋中“马走日”的行走法)从初始坐标位置(x1,y1)出发,要遍访(巡游)棋盘中的每一个位置一次。请编一个程序,为骑士求解巡游“路线图”(或告诉骑士,从某位置出发时,无法遍访整个棋盘 — 问题无解)。
tanhouyusheng
相关分类