解数独
#include<stdio.h>
#include<stdbool.h>
char grid[] =
{
5,3,0,0,7,0,0,0,0,
6,0,0,1,9,5,0,0,0,
0,9,8,0,0,0,0,6,0,
8,0,0,0,6,0,0,0,3,
4,0,0,8,0,3,0,0,1,
7,0,0,0,2,0,0,0,6,
0,6,0,0,0,0,2,8,0,
0,0,0,4,1,9,0,0,5,
0,0,0,0,8,0,0,7,9
};
#define length 60
int flag[length] = { 0 };
int index = 0;
bool isValid(int row, int col, char val, char grid[]) {
for (int j = 0; j < 9; j++) {
if (grid[row * 9 + j] == val) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if (grid[i * 9 + col] == val) {
return false;
}
}
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) { // 判断9方格里是否重复
for (int j = startCol; j < startCol + 3; j++) {
if (grid[i * 9 + j] == val) {
return false;
}
}
}
return true;
}
bool backtracking(char grid[]) {
for (int i = 0; i < 9; i++) { // 遍历行
for (int j = 0; j < 9; j++) { // 遍历列
if (grid[i * 9 + j] != 0) continue;
for (char k = 1; k <= 9; k++) { // (i, j) 这个位置放k是否合适
if (isValid(i, j, k, grid)) {
grid[i * 9 + j] = k; // 放置k
if (backtracking(grid))
{
flag[index] = k;
index++;
return true; // 如果找到合适一组立刻返回
}
grid[i * 9 + j] = 0; // 回溯,撤销k
}
}
return false; // 9个数都试完了,都不行,那么就返回false
}
}
return true; // 遍历完没有返回false,说明找到了合适棋盘位置了
}
int main() {
backtracking(grid);
printf("\n");
//输出数独表
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
printf("%d", grid[i * 9 + j]);
}
printf("\n");
}
//输出要填的数字
for (int i = length - 1; i >= 0; i--) {
printf("%d", flag[i]);
}
return 0;
}