Skip to content

Instantly share code, notes, and snippets.

@warm-ice0x00
Last active April 3, 2023 17:48
Show Gist options
  • Save warm-ice0x00/e6501c9682b6d218cdbfa1062b75a3f4 to your computer and use it in GitHub Desktop.
Save warm-ice0x00/e6501c9682b6d218cdbfa1062b75a3f4 to your computer and use it in GitHub Desktop.
#include <ctype.h>
#include <stdio.h>
unsigned char IsSafe(const unsigned char *const board, const unsigned char pos,
const unsigned char num) {
const unsigned char row = pos / 9, col = pos % 9, row_start = row / 3 * 27,
col_start = col / 3 * 3;
unsigned char i;
for (i = 0; i < 9; ++i)
if (board[row * 9 + i] == num || board[i * 9 + col] == num ||
board[row_start + i % 3 * 9 + col_start + i / 3] == num)
return 0;
return 1;
}
unsigned char Solve(unsigned char *board) {
unsigned char i;
unsigned char *p = board;
for (i = 0; i < 81; ++i, ++p) {
if (*p == 0) {
unsigned char num;
for (num = 1; num <= 9; ++num) {
if (IsSafe(board, i, num)) {
*p = num;
if (Solve(board)) return 1;
*p = 0;
}
}
return 0;
}
}
return 1;
}
void PrintSolution(unsigned char *board) {
if (Solve(board)) {
unsigned char i;
for (i = 0; i < 81; ++i) {
printf("%u", *board++);
if (i % 9 == 8) putchar('\n');
}
} else
puts("No solution");
}
unsigned char ReadInput(unsigned char *arr) {
const unsigned char *const end = arr + 81;
int c;
while (arr < end) {
c = getchar();
if (isdigit(c))
*arr++ = c - '0';
else if (c == '.')
*arr++ = 0;
else
return 0;
}
while ((c = getchar()) != '\n' && c != EOF)
;
return 1;
}
int main() {
unsigned char board[81];
while (1)
if (ReadInput(board)) PrintSolution(board);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment