int chesssearch(int x,int y, int j) { /*save the value x,y*/ int x1 = x, y1 = y; int flag = 0, i = 0, result = 0; /*recursion exit condition*/ if(j == COLS*ROWS) { return 1; } for(i = 0; i < 8; i++) { flag = nextxy(&x1,&y1,i);//八个方向 if(flag == 1) { chess[x1][y1] = j; result = chesssearch(x1,y1,j+1); if(result == 1) { return 1; }else { chess[x][y] = 0; x1 = x; y1 = y; } } } return 0; }
// 深度优先遍历棋盘 // (x,y)为位置坐标 // tag是标记变量,每走一步,tag+1 int TravelChessBoard(int x, int y, int tag) { int x1=x, y1=y, flag=0, count=0; chess[x][y] = tag; if( X*Y == tag ) { // 打印棋盘 print(); return 1; } // 寻找出下一次马可以走的位置 flag = nextxy(&x1, &y1, count); while(0==flag && count<7) { count++; flag = nextxy(&x1, &y1, count); } while(flag) { if(TravelChessBoard(x1, y1, tag+1)) { return 1; } x1 = x; y1 = y; count++; flag = nextxy(&x1, &y1, count); while(0==flag && count<7) { count++; flag = nextxy(&x1, &y1, count); } } if(0 == flag) { chess[x][y] = 0; } return 0; }
int deepsearch(int x,int y, int j) { /*save the value x,y*/ int x1 = x, y1 = y; int tag = 0, i = 0; /*save j on chess[x][y]*/ chess[x][y] = j; /*recursion exit condition*/ if(j == COLS*ROWS) { return 1; } /*find the next point in eight directions*/ tag = nextxy(&x1,&y1,i); /*find the nextx,nexty */ while (tag == 0 && i < 7) { i++; tag = nextxy(&x1,&y1, i); } /*the nextxy be found*/ while(tag) { if(deepsearch(x1,y1,j+1)) return 1; /*if failed, a new finding process */ x1 = x; y1 = y; i++; tag = nextxy(&x1,&y1,i); while (tag == 0 && i < 7) { i++; tag = nextxy(&x1,&y1,i); } } /*no direction can find next point*/ if(tag == 0) chess[x][y] = 0; return 0; }