//http://w...content-available-to-author-only...s.org/archives/12916

#include <stdio.h>
#define N 8

int isSafe(int x, int y, int soln[][N])
{
	if(x>=0 && x<N && y>=0 && y<N && soln[x][y]==-1){
		return 1;
	}
	return 0;
}

int generateMoves(int x, int y, int moveNum, int soln[][N], int xMoves[], int yMoves[])//making move number 'moveNum' from x and y.
{
	if(moveNum == N*N){
		return 1;
	}
	else{
		int i, nextX, nextY;
		for(i=0; i<8; ++i){
			nextX = x + xMoves[i];
			nextY = y + yMoves[i];
			
			if(isSafe(nextX, nextY, soln)){
				soln[nextX][nextY] = moveNum;
				if( generateMoves(nextX, nextY, moveNum+1, soln, xMoves, yMoves) ){
					return 1;
				}
				else{
					soln[nextX][nextY] = -1;
				}
			}
		}
		return 0;
	}
}

void printSoln(int soln[][N])
{
	int i, j;
	for(i=0; i<N; ++i){
		for(j=0; j<N; ++j){
			printf("%2d ", soln[i][j]);
		}
		printf("\n");
	}
}	

void moveKnight()
{
	int soln[N][N];
	int i, j;
	for(i=0; i<N; ++i){
		for(j=0; j<N; ++j){	
			soln[i][j] = -1;
		}
	}
	
	int xMoves[] = {2, 2, 1, 1, -1, -1, -2, -2};
	int yMoves[] = {1, -1, -2, 2, -2, 2, -1, 1};

	soln[0][0] = 0; //making the first move i.e. putting the knight at (0, 0)
	if( generateMoves(0, 0, 1, soln, xMoves, yMoves) ){
		printSoln(soln);
	}
	else{
		printf("\nNOT POSSIBLE\n");
	}
}

int main()
{
	moveKnight();
	return 0;
}