好吧所以我有一个数独求解器的所有这些代码(它没有完成,我仍然需要我找到下一个函数和合法移动函数)但我可以使用一些打印帮助。代码要求用户上传要读取的文件,然后打印出拼图。这意味着数独可以是3x3或4x4,一直到25x25。我需要帮助的是,在我的print_puzzle函数中,如何确保它以块的形式打印出来?就像它是3x3一样,这个拼图会有9个3x3盒子。希望这很有意义,反正这里是代码:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
bool prompt_for_file (void);
bool load_puzzle(char filename[]);
void print_puzzle (void);
bool solve_puzzle(void);
bool find_next( int *row, int *col, int dir);
bool legal_move(int num; int row; int col);
#define MAX_SIZE 25
#define FORWARD 1
#define BACKWARD 0
int puzzle[MAX_SIZE][MAX_SIZE];
int puzzle_size;
int block_size;
int main(void)
{
if (!prompt_for_file())
{return -1;}
print_puzzle();
if (solve_puzzle())
{print_puzzle();}
else
{return -1;}
return 0;
}
bool solve_puzzle(void)
{
int dir;
int R;
int C;
int n;
int previous_n;
dir = FORWARD;
while(find_next(&R, &C, dir))
{
dir= BACKWARD;
previous_n=abs(puzzle[R][C]);
puzzle[R][C]= 0;
for (n=previous_n+1; n<=puzzle_size; n++)
{
if (legal_move(n, R, C))
{
puzzle[R][C] = -n;
dir = FORWARD;
break;
}
}
}
if (dir== FORWARD)
{return true;}
else
{return false;}
}
void print_puzzle (void)
{
int r;
int c;
printf("\n");
for (r=0;r<puzzle_size;r++)
{
for (c=0;c<puzzle_size;c++)
{
printf("%3d", abs(puzzle[r][c]));
//put something in to define blocks
}
printf("\n");
}
printf("\n");
}
/*
bool find_next( int *row, int *col, int dir)
{
*R=r;
*C=c;
}
*/
bool prompt_for_file (void)
{
char filename[100];
do
{
printf("Enter a file name (or ""quit""): ");
scanf("%s",&filename[0]);
if ( strcmp(filename,"quit")==0 )
{
filename[0]='\0';
printf("quitting\n");
return false;
}
} while( load_puzzle(filename)!=true );
return true;
}
bool load_puzzle(char filename[])
{
int r;
int c;
int dummy;
FILE *fileptr;
// open the file but return if not successful
fileptr = fopen(filename,"r");
if ( fileptr==NULL)
{
printf("the file was not opened: %s\n", filename);
return false;
}
else
{
printf("the file was opened: %s\n", filename);
}
// read the sizing info
fscanf(fileptr,"%d",&puzzle_size);
printf("the number of rows and cols: %d\n",puzzle_size);
if (puzzle_size>MAX_SIZE)
{
printf("puzzle is too big %d. Max size is %d\n", puzzle_size,MAX_SIZE);
return false;
}
block_size=sqrt(puzzle_size);
// read the data
for (r=0;r<puzzle_size;r++)
{
for (c=0;c<puzzle_size;c++)
{
if ( fscanf(fileptr,"%d",&puzzle[r][c])!=1 )
{
printf("insufficient number of elements\n");
return false;
}
}
}
// check to see if all of the data was read
// and that the end of the input file has been reached
if (fscanf(fileptr,"%d",&dummy) ==1)
{
printf("WARNING: not all numbers from file were used.\n");
}
if (feof(fileptr))
{
printf("The end of the input file has been reached.\n");
}
fclose(fileptr);
return true;
}
谢谢!! :)