#include <stdio.h>
typedef int boardtype[9+1][9+1];

typedef int bool;
const bool TRUE = 1;
const bool FALSE = 0;

typedef struct {int x, y;} point;
bool finished;
// for detecting no solution:
point first_with_choice = {0,0};

point next_point(point pt);
bool done(point p);
bool valid(point p, int value, boardtype board);
void process_solution(boardtype board);
void backtrack_sudoku(point pt, int value, boardtype board);
  // if point is beyond board, we're done, report result.
  // if pt is occupied (by input value) go to next point
  // if it is valid, commit to the move and try to complete solution
  // but if this is last value (9), backtrack

void backtrack_sudoku(point pt, int value, boardtype board) {
  // pt, value denotes a potential next move
  // if point is beyond board, we're done, report result.
  if (done(pt)) // is_a_solution(pt, board); 
  {	process_solution(board); finished = TRUE; }
  // if pt is occupied (by input value) go to next point
  else if (board[pt.x][pt.y] > 0)
    backtrack_sudoku(next_point(pt), 1, board);
  else 
  {  
    // for detecting no solution 
    if (first_with_choice.x == 0) first_with_choice = pt;
    // if it is valid, use it and continue to next point, value 1
    if (valid(pt, value, board)) {      
      board[pt.x][pt.y] = value; // make move
      backtrack_sudoku(next_point(pt), 1, board);
      if ( ! finished )
          board[pt.x][pt.y] = 0; // unmake move
    }
    // if it is invalid or valid but didn't yield a complete solution, continue to next value
    if ( !finished && value < 9)
        backtrack_sudoku(pt, value+1, board);
    // 
    else 
        // for detecting no solution 
		if (!finished && 
			 first_with_choice.x == pt.x && 
			 first_with_choice.y == pt.y)
        printf("No Solution\n");
  }
  // but if this is last value (9), backtrack
}

point next_point(point pt) {
	point next = pt;
	if (next.y < 9) next.y += 1;
    else {next.y = 1; next.x += 1;}
	return next;
}

bool done(point p) { return p.x > 9; }

bool valid(point p, int value, boardtype board) {
//check row: that for each j board[pt.x][j] != value 
//check col: that for each i board[i][pt.y] != value 
//check block: that for each i,j in 3 by 3 block of point, board[i][j] != value
return rand()%7 > 0 ? FALSE : TRUE;
}

void process_solution(boardtype board) {
	printf("Solved!\n");
}

int main(){
	srand(time(NULL)); // for fake validity check

	point p; p.x = p.y = 1;
    boardtype board;
    // must initialize board
	board[1][1] = board[1][2] = 1;
    finished = FALSE;
	backtrack_sudoku (p, 1, board);
    // alternate -- and simpler -- way to detect no solution found
    if (! finished) printf("Yes, we have no solution\n");
}

