贪心算法::启发式搜索解决马跳棋盘问题

#include <stdio.h>
#include <WINDOWS.H>
int QIPAN[8][8] = {0};
int reach[8][2] ={	-2,1,
					-2,-1,
					-1,2,
					-1,-2,
					 1,2,
					 1,-2,
					 2,1,
					 2,-1  };
int N = 0;
int output(){
	int i,j;
	system("cls");
	printf("  0  1  2  3  4  5  6  7 \n\n");
	for (i=0; i<8; i++){
		for (j=0; j<8; j++){
			if ( QIPAN[i][j] == 0 ) {
				printf("   ");
			} else {
				printf("%3d", QIPAN[i][j]);
			}
		}
		printf("\n");
	}
	printf("===================\n");
}
int count(int x, int y){
	int n,i,tmpx,tmpy;
	n=0;
	for (i=0; i<8; i++){
		tmpx = reach[i][0]+x;
		tmpy = reach[i][1]+y;
		if (tmpx>=0 && tmpx<8 && tmpy>=0 && tmpy<8 && QIPAN[tmpx][tmpy]==0 ) {
			n++;
		}
	}
	return n;
}
int solve(int x, int y, int k){
	int i;
	int tmpx,tmpy,bestx,besty;
	int min,n;
	
	if ( k>8*8)
	{
		output();
		getch();
		return 0;
	}
	
	QIPAN[x][y] = k;
	min = 8+1;
	for (i=0; i<8; i++){
		tmpx = reach[i][0]+x;
		tmpy = reach[i][1]+y;
		if ( tmpx>=0 && tmpx<8 && tmpy>=0 && tmpy<8 && QIPAN[tmpx][tmpy]==0 )
		{
			n = count(tmpx, tmpy);
			if ( n < min) {
				min = n;
				bestx = tmpx;
				besty = tmpy;
			}
		}
	}
	
	output();
	//getch();
	solve(bestx, besty, k+1);
}
int main() {
	int x,y;
	x=0;
	y=0;
	solve(x, y, 1);
	return 0;
}



你可能感兴趣的:(算法,启发,贪心,棋盘,马)