提交时间:2024-08-21 17:56:49

运行 ID: 180725

#include<stdio.h> #include<iostream> #define SIZE 3 using namespace std; void travel(int x, int y, int num, int route[], int map[][SIZE + 4]);//递归函数,在当前(x,y)坐标下的走法,确定route[num]值 bool cut(int x, int y, int i, int map[][SIZE + 4]);//剪枝函数,在(x,y)坐标下能否向i方向走 void print(int route[]);//打印路线 int result = 1; int direction[8][2] = { {2,1}, {1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1} };//八个方向 int main() { int map[SIZE + 4][SIZE + 4] = {0}; int route[SIZE * SIZE] = {0}; //方向数组 int i,j; //地图初始化 for(j = 0; j < SIZE + 4; j++){ map[0][j] = 1; map[1][j] = 1; map[SIZE + 2][j] = 1; map[SIZE + 3][j] = 1; } for(i = 0; i < SIZE + 2; i++){ map[i][0] = 1; map[i][1] = 1; map[i][SIZE + 2] = 1; map[i][SIZE + 3] = 1; } int x,y; cin>>x>>y;//输入起始横纵坐标 x++; y++; map[x][y] = 1; travel(x, y, 1, route, map);//在当前坐标下开始走 return 0; } void travel(int x, int y, int num, int route[], int map[][SIZE + 4]){ int i; //返回条件,当走完所有格子 if(num == SIZE * SIZE - 1){ print(route); return; } //遍历每一种方向 for( i = 0; i < 8; i++){ cout<<"*"<<endl; //如果i方向能走 if(cut(x,y,i,map)){ cout<<num<<x - 1<<" "<<y - 1<<i<<endl; route[num] = i; x += direction[i][0]; y += direction[i][1]; map[x][y] = 1; num++; travel(x, y, num, route, map); } } //如果没有办法走 if(i == 8){ cout<<"走到"<<num<<"的时候不通"<<endl; return; } } bool cut(int x, int y, int i, int map[][SIZE + 4]){ x += direction[i][0]; y += direction[i][1]; if(map[x][y] == 1){ return false; } else{ return true; } } void print(int route[]){ int i; cout<<result; for(i = 1; i < SIZE * SIZE; i++){ cout<<route[i]<<" "; } cout<<endl; }