Skip to content

Instantly share code, notes, and snippets.

@awsum
Created November 5, 2016 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awsum/c2cc209fed1385c0aa400a1f88f58407 to your computer and use it in GitHub Desktop.
Save awsum/c2cc209fed1385c0aa400a1f88f58407 to your computer and use it in GitHub Desktop.
#include <stdio.h>
const int GRID_SIZE = 9;
void print(int grid[GRID_SIZE][GRID_SIZE]) {
for (int i=0;i<GRID_SIZE;i++) {
for (int j=0;j<GRID_SIZE;j++) {
printf("%d", grid[i][j]);
if (j < GRID_SIZE-1) {
printf(" ");
}
}
printf("\n");
}
}
int fits(int grid[GRID_SIZE][GRID_SIZE], int row, int col, int n)
{
int rs = (row/3) * 3;
int cs = (col/3) * 3;
for(int i=0; i<GRID_SIZE; i++) {
if (grid[row][i] == n) {
return 0;
}
if (grid[i][col] == n) {
return 0;
}
if (grid[rs+(i%3)][cs+(i/3)] == n) {
return 0;
}
}
return 1;
}
int rsolve(int grid[GRID_SIZE][GRID_SIZE], int row, int col) {
if (row == GRID_SIZE && col == GRID_SIZE) {
return 1;
}
if (grid[row][col] != 0) {
if ( col < GRID_SIZE-1) {
return rsolve(grid, row, col+1);
} else if (row < GRID_SIZE-1) {
return rsolve(grid, row+1, 0);
}
return 1;
}
for (int n=0; n<GRID_SIZE; n++) {
if (fits(grid, row, col, n+1)) {
grid[row][col] = n+1;
if (col < GRID_SIZE-1) {
if (rsolve(grid, row, col+1)) {
return 1;
}
grid[row][col] = 0;
}
else if (row < GRID_SIZE-1) {
if (rsolve(grid, row+1, 0)) {
return 1;
}
grid[row][col] = 0;
}
else {
return 1;
}
}
}
return 0;
}
void solve(int grid[GRID_SIZE][GRID_SIZE]) {
rsolve(grid, 0, 0);
}
int main(int argc, char *argv[]) {
if (argc != GRID_SIZE+1) {
return 1;
}
int grid[GRID_SIZE][GRID_SIZE];
for (int i=0; i<GRID_SIZE; i++) {
for (int j=0; j<GRID_SIZE; j++) {
char c = argv[i+1][j];
grid[i][j] = c == '.' ? 0 : c - '0';
}
}
solve(grid);
print(grid);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment