C语言:马踏棋盘,改编自《数据结构与算法》.

来源:互联网 发布:新网域名个人备案 编辑:程序博客网 时间:2024/06/10 07:33
#include<stdio.h>#include<stdlib.h>#define stack_size 100#define n 8int a[n][n];int sort[n][n][8];int i, j, k,h,l;struct seat{int x, y;//坐标int direct;};struct stack{struct seat *top, *base;};struct stack s;int initstack(){s.base=(struct seat*)malloc( stack_size*sizeof(struct seat) );if( !s.base )return 0;s.top=s.base;return 1;}void push(struct seat elem){*s.top++=elem;}int pop(){if(s.top==s.base)return 0;s.top--;return 1;}struct seat gettop(){if(s.top==s.base)exit(0);return *(s.top-1);}int empty(){if(s.top==s.base)return 0;return 1;}int pass(struct seat point){struct seat *head=s.top;if(point.x<0 || point.x>n-1 || point.y<0 || point.y>n-1){return 0;}while(head != s.base){head--;if(point.x==head->x && point.y==head->y)return 0;}return  1;}struct seat next_point(struct seat point, int direct){switch(direct){case 1:point.x+=1, point.y-=2;break;case 2:point.x+=2, point.y-=1;break;case 3:point.x+=2,point.y+=1;break;case 4:point.x+=1,point.y+=2;break;case 5:point.x-=1,point.y+=2;break;case 6:point.x-=2,point.y+=1;break;case 7:point.x-=2,point.y-=1;break;case 8:point.x-=1,point.y-=2;break;}return point;}void setweight(){struct seat point1, point2;for(i=0; i<n; i++)for(j=0; j<n; j++){a[i][j]=0;point1.x=i;point1.y=j;for(k=1; k<=8; k++){point2 = next_point(point1, k);if(point2.x>=0 && point2.x<=n-1 && point2.y>=0 && point2.y<=n-1)a[i][j]++;}}}void next_direct(){struct seat point1, point2;int  count[8], min, r;for(i=0; i<n; i++)for(j=0; j<n; j++){point1.x=i;point1.y=j;for(k=0; k<8; k++){point2 = next_point(point1, k+1);//现在点的8个方向可走点的:下一个位置if(point2.x>=0 && point2.x<=n-1 && point2.y>=0 && point2.y<=n-1)count[k]=a[point2.x][point2.y];elsecount[k]=0;}for(h=0; h<8; h++){min=9;for(l=0; l<8; l++){    if(min > count[l]){min=count[l];sort[i][j][h]=l;//可走的方向由小到大r=l;//标志最小可走的方向}}count[r]=9;//选过的设为比8大的数}}}int horse_stack(struct seat start){struct seat next_seat;int next_direct;int horsestep=0;start.direct=0;next_seat=start;do{if( pass(next_seat) ){horsestep++;push(next_seat);if(horsestep==n*n)return 0;next_direct=sort[(s.top-1)->x][(s.top-1)->y][(s.top-1)->direct]+1;next_seat = next_point( *(s.top-1), next_direct);//贪心策略,试着走下一步,还未入栈next_seat.direct=0;}else{while( empty() && (s.top-1)->direct==7){pop();horsestep--;}if( empty() && (s.top-1)->direct<7){next_direct = sort[(s.top-1)->x][(s.top-1)->y][++(s.top-1)->direct]+1;next_seat = next_point( *(s.top-1), next_direct);next_seat.direct=0;}}}while( empty() );return 1;}void output(){int path[n][n];struct seat *point=s.base;for(i=0; point != s.top; i++){path[point->x][point->y]=i+1;point++;}for(i=0; i<n; i++){printf("\n");for(j=0; j<n; j++){printf("\t%d", path[i][j]);}}printf("\n");}void main(){struct seat start;printf("start x(0--7): ");scanf("%d", &start.x);printf("\nstart y(0--7): ");scanf("%d", &start.y);start.direct=0;initstack();setweight();next_direct();horse_stack(start);output();}

0 0