馬的遍歷問題
在n*m的棋盤中,馬只能走“日” 字。馬從位置(x,y)處出發,把棋盤的每一格都走一次,且只走一次。找出所有路徑。
問題解的搜索空間?
棋盤的規模是n*m,是指行有n條邊,列有m條邊。
馬在棋盤的點上走,所以搜索空間是整個棋盤上的n*m個點。
用n*m的二維數組記錄馬行走的過程,初值爲0表示未經過。
在尋找路徑過程中,活結點的擴展規則?
對於棋盤上任意一點A(x,y),有八個擴展方向:
A(x+1,y+2),A(x+2,y+1)
A(x+2,y-1),A(x+1,y-2)
A(x-1,y-2),A(x-2,y-1)
A(x-2,y+1),A(x-1,y+2)
爲構造循環體,用數組fx[8]={1,2,2,1,-1,-2,-2,-1},fy[8]= {2,1,-1,-2,-2,-1,1,2}來模擬馬走“日”時下標的變化過程。
不出邊界;
每個點只經過一次。
棋盤點對應的數組元素初值爲0,對走過的棋盤點的值置爲所走步數,起點存儲“1”,終點存儲“n*m”。
函數check,檢查當前狀態是否合理
0 0
1 90 82 75 88 83 78 85 89
71 74 2 64 81 76 87 84 79
44 55 72 69 3 63 80 77 86
73 70 45 56 65 68 4 62 59
54 43 66 51 46 57 60 49 5
41 37 53 31 67 50 47 58 61
35 12 42 38 52 30 25 6 48
20 39 36 13 32 23 16 29 26
11 34 21 18 9 14 27 24 7
40 19 10 33 22 17 8 15 28
#include <stdio.h>
#include <string.h>
int matrix[10][9];
int journey = 1;
int step_x[]={1,2,2,1,-1,-2,-2,-1},step_y[]={2,1,-1,-2,-2,-1,1,2};
void outMatrix(){
int i,j;
for (i=0;i<10;i++)
{
for (j=0;j<9;j++)
{
printf("%-2d ",matrix[i][j]);
}
printf("\n");
}
}
bool outofbounds(int x,int y){
return x < 0 || y < 0 || x >= 10 || y >= 9;
}
bool isCome(int x,int y){
return matrix[x][y];
}
void gotoend(int x, int y ){
if(journey>90) return;
int i;
matrix[x][y]=journey++; //當前是第幾步
for (i = 0;i<8;i++)
{
int next_x = x+step_x[i];
int next_y = y+step_y[i];
if(!outofbounds(next_x,next_y) && !matrix[next_x][next_y]){
gotoend(next_x,next_y);
}
}
}
int main(){
int start_x,start_y;
int i;
scanf("%d%d",&start_x,&start_y);
for (i = 0;i<10;i++) {
memset(matrix[i],0,sizeof(matrix[0]));
}
gotoend(start_x,start_y);
outMatrix();
return 0;
}