1个回答
展开全部
我从网上随便找个一个帮你改了改。首先把你要解的数独放入一个文件sudo_input里,和你编译后的exe文件在同一目录。内容为:
1 0 0 0
0 0 0 2
0 0 4 0
0 3 0 0
代码如下(备注:基本上这个也可以做9路甚至更多的,只需改动LENGTH和SUBLEN值即可):
#include <stdlib.h>
#include <stdio.h>
#define LENGTH 4
#define SUBLEN 2
int answer = 0;
void printSudo(int array[][LENGTH]) {
printf("\n\n");
int i, j;
for (i = 0; i < LENGTH; i++) {
if ((i + 1) % SUBLEN == 0)
printf("\n\n");
for (j = 0; j< LENGTH; j++) {
if ((j + 1) % SUBLEN == 0)
printf("\t");
printf("%d ", array[i][j]);
}
printf("\n");
}
exit(0);
}
void initSudoArray(int array[][LENGTH]) {
int i, j;
FILE *fp;
if ((fp = fopen("sudo_input", "r")) == NULL) {
printf("File open failed !\n");
exit(-1);
}
for (i = 0; i < LENGTH; i++) {
for (j = 0; j < LENGTH; j++) {
fscanf(fp, "%d", &array[i][j]);
}
}
fclose(fp);
}
int checkSudo(int array[][LENGTH], int i, int j, int testVal) {
int row, col;
printf("checkSudo for [%d][%d] testVal = %d\n", i, j, testVal);
// fixed to col j, check for the rows
for (row = 0; row < LENGTH; row++) {
printf("check for rows! [%d][%d] = %d\n", row, j, array[row][j]);
if (array[row][j] == testVal)
return 0;
}
// fixed to row i, check for cols
for (col = 0; col < LENGTH; col++) {
printf("check for cols! [%d][%d] = %d\n", i, col, array[i][col]);
if (array[i][col] == testVal)
return 0;
}
//check for the sub-square
int row_subSquare = (i / SUBLEN) * SUBLEN;
int col_subSquare = (j / SUBLEN) * SUBLEN;
printf("[%d][%d]\n", row, col);
for (row = row_subSquare; row < row_subSquare + SUBLEN; row++) {
for (col = col_subSquare; col < col_subSquare + SUBLEN; col++) {
printf("check for sub-square! [%d][%d] = %d\n", row, col, array[row][col]);
if (array[row][col] == testVal)
return 0;
}
}
return 1;
}
// length is the plane index of the sudo array
void sudo_solve(int array[][LENGTH], int length) {
// i for rows, j for cols
int i, j;
int testVal;
int tempArray[LENGTH][LENGTH];
//dump the array to tempArray
for (i = 0; i < LENGTH; i++) {
for (j = 0; j < LENGTH; j++)
tempArray[i][j] = array[i][j];
}
i = length / LENGTH;
j = length % LENGTH;
printf("array[%d][%d] = %d", i, j, array[i][j]);
if (array[i][j] != 0) {
// there is a val in the slot array[i][j]
if (length == 80)
printSudo(tempArray);
else
sudo_solve(tempArray, length + 1);
} else {
// there is no val in the slot array[i][j]
for (testVal = 1; testVal <= LENGTH; testVal++) {
if (checkSudo(tempArray, i, j, testVal) != 0) {
tempArray[i][j] = testVal;
if (length == LENGTH * LENGTH - 1)
printSudo(tempArray);
else
sudo_solve(tempArray, length + 1);
tempArray[i][j] = 0;
}
}
}
}
int main(void) {
int array[LENGTH][LENGTH];
initSudoArray(array);
sudo_solve(array, 0);
if (answer == 0)
printf("There is no answer for this sudo!");
return 0;
}
追问
能够简单点吗,不读取文件。
追答
你把initSudoArray改成数组赋值不就完了吗?这么简单,你也动动手动动脑子,对你有好处的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询