I've been fooling with this all day. I need some advice solving what I believe is a logic error.I'm trying to find someone who can tell me why this code only works for a 7X7 chessboard or smaller. If I make the size to be 8X8 it never completes the process. If it's no trouble, I hope someone can help lead me to a solution. Thanks!
Code:
#include <stdio.h>
#include <stdlib.h>
#define N 8
int board[N][N];
void print_board()
{
int i, j;
for (i=0; i<N; ++i)
{
for (j=0; j<N; ++j)
printf("%5d", board[i][j]);
printf("\n\n");
}
}
int Range(int row, int col)
{
if (row>=0 && row<N && col>=0 && col<N)
return 1;
return 0;
}
int need_visit(int row, int col)
{
return (Range(row,col) && board[row][col]==0);
}
//move[8][2] is the possible move destinations
void next_move(int row, int col, int move[8][2], int *n)
{
*n = 0;
if (need_visit(row-2,col-1)) { move[*n][0]=row-2; move[(*n)++][1]=col-1; }
if (need_visit(row-2,col+1)) { move[*n][0]=row-2; move[(*n)++][1]=col+1; }
if (need_visit(row-1,col-2)) { move[*n][0]=row-1; move[(*n)++][1]=col-2; }
if (need_visit(row-1,col+2)) { move[*n][0]=row-1; move[(*n)++][1]=col+2; }
if (need_visit(row+1,col-2)) { move[*n][0]=row+1; move[(*n)++][1]=col-2; }
if (need_visit(row+1,col+2)) { move[*n][0]=row+1; move[(*n)++][1]=col+2; }
if (need_visit(row+2,col-1)) { move[*n][0]=row+2; move[(*n)++][1]=col-1; }
if (need_visit(row+2,col+1)) { move[*n][0]=row+2; move[(*n)++][1]=col+1; }
}
int continue(int row, int col)
{
int move[8][2], move_num;
if(temp==N*N)
return 1;
next_move(row, col, move, &move_num);
while(move_num--)
{
int move_row = move[move_num][0];
int move_col = move[move_num][1];
board[move_row][move_col] = ++temp;
if (continue(move_row,move_col))
return 1;
board[move_row][move_col] = 0;
--temp;
}
return 0;
}
int main()
{
int StartRow,StartCol, temp;
print_board();
printf( "please enter the starting row ");
scanf( "%d", &StartRow );
printf( "\n" );
printf( "please enter the starting col " );
scanf( "%d", &StartCol );
board[StartRow][StartCol]=1;
temp = 1;
print_board();
}
return 0;