思路
栈和队列不太会,这是用递归写的
#include<iostream>
#include<cstdio>
#define N 8
using namespace std;
int board[N][N];
int cnt=1;
int solve(int i,int j){
//1
if((i-2>=0)&&(i-2<=7)&&(j+1>=0)&&(j+1<=7)){
if(!board[i-2][j+1]){
board[i-2][j+1]=cnt;
cnt++;
solve(i-2,j+1);
}
}
//2
if((i-1>=0)&&(i-1<=7)&&(j+2>=0)&&(j+2<=7)){
if(!board[i-1][j+2]){
board[i-1][j+2]=cnt;
cnt++;
solve(i-1,j+2);
}
}
//3
if((i+1>=0)&&(i+1<=7)&&(j+2>=0)&&(j+2<=7)){
if(!board[i+1][j+2]){
board[i+1][j+2]=cnt;
cnt++;
solve(i+1,j+2);
}
}
//4
if((i+2>=0)&&(i+2<=7)&&(j+1>=0)&&(j+1<=7)){
if(!board[i+2][j+1]){
board[i+2][j+1]=cnt;
cnt++;
solve(i+2,j+1);
}
}
//5
if((i+2>=0)&&(i+2<=7)&&(j-1>=0)&&(j-1<=7)){
if(!board[i+2][j-1]){
board[i+2][j-1]=cnt;
cnt++;
solve(i+2,j-1);
}
}
//6
if((i+1>=0)&&(i+1<=7)&&(j-2>=0)&&(j-2<=7)){
if(!board[i+1][j-2]){
board[i+1][j-2]=cnt;
cnt++;
solve(i+1,j-2);
}
}
//7
if((i-1>=0)&&(i-1<=7)&&(j-2>=0)&&(j-2<=7)){
if(!board[i-1][j-2]){
board[i-1][j-2]=cnt;
cnt++;
solve(i-1,j-2);
}
}
//8
if((i-2>=0)&&(i-2<=7)&&(j-1>=0)&&(j-1<=7)){
if(!board[i-2][j-1])
{
board[i-2][j-1]=cnt;
cnt++;
solve(i-2,j-1);
}
}
}
int main(){
int x,y;
printf("please input init x,y:");
scanf("%d%d",&x,&y);
solve(x,y);
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(board[i][j]){
solve(i,j);
}
}
}
printf(" |");
for(int i=0;i<8;i++)
printf("%3d ",i);
printf("\n ------------------------------------\n");
for(int i=0;i<N;i++){
printf("%3d |",i);
for(int j=0;j<N;j++){
printf("%3d ",board[i][j]);
}
printf("\n");
}
return 0;
}
图片演示
初始位置
行走过程