示例#1
0
文件: su.c 项目: ragilr/sudoku-solver
void solve_sudoku(int n)
{
    int p,q,i;
    if(n==81)
    {
        print_ans();
        fill(a,ans,LIGHTGRAY);
        exit(0);
    }
    p=n/9; q=n%9;
    if(ans[p][q]==0)
    {
        for(i=1;i<=9;++i)
        {
            if(place(i,p,q))
            {
                ans[p][q]=i;
                solve_sudoku(n+1);
                ans[p][q]=0;
            }
        }
    }
    else
        solve_sudoku(n+1);
}
/*
 *  Function: solve sudoku
 *  This is the 'heart'  of the program. solve_sudoku is a recursive function
 *  which solves the given sudoku.
 *  Imput arguments: 
 *   int *problem : pointer where the sudoku is stored
 *  Return:
 *   1 if there is an error
 *   0 otherwise
 */
int solve_sudoku(int *problem)
{
  int *ptr;
  int i=0;
  ptr=problem;
  int solve=1;
  // Looking for first non-zero (i.e. blank) character
  while((*ptr!=0))
    {
      ptr++;
      i++;
      //If we are in the last cell, return Ok!
      if (i==82)
	{
	  return 0;
	}
    }
  // We write the first valid number in that position
  (*ptr)=1;
  while(check_all(problem)!=0)
    {
      (*ptr)++;
      if ((*ptr)==10)
	{
	  // If there is not a valid number, we write a 0 and return an error
	  (*ptr)=0;
	  return 1;
	}
    }
  // If there is a number, we call the function solve_sudoku with the new sudoku.
  solve=solve_sudoku(problem);  
  // If we are returned a '1' (problem!) we increment the cell and call the function again.
  // If we can't increment the cell more, we write a 0 and return an error.
  while(solve==1)
    {

      (*ptr)++;

      if ((*ptr)==10)
	{
	  (*ptr)=0;
	  return 1;
	}
      solve=solve_sudoku(problem);
    }
  
  // If we reach this instruction, all is good.
  return 0;
}
示例#3
0
文件: sudoku.c 项目: jkim664/junik
// Procedure: solve_sudoku
// Solve the given sudoku instance.
int solve_sudoku(int sudoku[9][9]) {

  // BEG TODO.		
	int i, j;
	
	if(cell_check(&i, &j, sudoku) == 1)		//check if the sudoku board is all filled out
		return 1;

	else
	{
		for(int val = 1; val <= 9; val++)	
		{
			if(is_val_valid(val, i, j, sudoku) == 1) 	//if the board is not full, check if a value can be input into the cell.
			{	
				sudoku[i][j] = val;			//if valid, insert the value into the cell.
				if(solve_sudoku(sudoku) == 1)		//solve the board with this value in place of the cell.
				{		
					return 1;
				}
				sudoku[i][j] = 0;			//if not solvable with this value in the cell, try next value++.
			}
		}	
	}	
				



  return 0;
  // END TODO.
}
示例#4
0
int main(int argc, char *argv[])
{
	int Board[SIZE][SIZE] = { 
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},
		{0, 0, 0, 0, 0, 0, 0, 0, 0},  
	};

	if(argc == 2) {
		FILE *fp;
		fp = fopen(argv[1], "r");
		int i, j;
		for(i=0; i<9; ++i) {
			for(j=0; j<9; ++j) {
				fscanf(fp, "%1d", &Board[i][j]);
			}
		}
	}
	
	if(solve_sudoku(Board) == -1)
		printf("Not Solvable!\n");
	else
		print(Board);
	
	return 0;
}
int main(int argc, char *argv[])
{
  int sudoku[81];
  int *ptr;
  int i;
  i=0;
  if (argc!=2)
    {
      printf("USAGE: ./sudoku_solver FILENAME\n");
      printf("FILENAME is the file where the sudoku is stored. It has to be a string of 81 integers from 0 to 9, without spaces\n");
      printf("The 0's represent the blank cells\n");
      return 1;
    }
  // Open File
  if(!(file_2_sudoku(sudoku,argv[1])))
    printf("[FILE 2 SUDOKU] File format not valid");
  // Check that the given sudoku is valid
  if (check_all(sudoku))
    {
      printf("Error. Invalid Sudoku.\n");
      return 1;
    }
  printf("Problem\n");
  print_sudoku(sudoku);
  printf("Solving... Be patient!\n");
  solve_sudoku(sudoku);
  printf("Solution\n");
  print_sudoku(sudoku);
  return 0;
}
示例#6
0
int solve_sudoku(int line, int column, int sudoku[9][9]) {
  int index_line, index_column, copy_sudoku[9][9], good=0, number;

  // create a sudoku matrix copy
  for(index_line=0; index_line<9; index_line++) {
    for(index_column=0; index_column<9; index_column++) {
      copy_sudoku[index_line][index_column] = sudoku[index_line][index_column];
    }
  }

  // go to the first 0 element
  while(copy_sudoku[line][column] != 0 && line < 9) {
    if (column == 8) {
      column = 0; line++;
    } else {
      column++;
    }
  }

  // if we are at the last line + 1 => we found a solution
  if (line >= 9) {
    print_solution(copy_sudoku);
    return 1;
  }

  // we are at 0-element in matrix, so we try to change that element with the
  // right non-0 element
  for(number=1; number<=9; number++) {
    // if the number meet thoese 3 condition, go to next position
    if (check_number(number, line, column, copy_sudoku)) {
      good = 1;
      copy_sudoku[line][column] = number;
      // continue solving for next position
      if (column == 8) {
        solve_sudoku(line+1, 0, copy_sudoku);
      } else {
        solve_sudoku(line, column+1, copy_sudoku);
      }
    }
    // if no solution was found, go back and try with another number
  }

  if (!good) return 0;
}
示例#7
0
文件: su.c 项目: ragilr/sudoku-solver
int main()
{
    initwindow(600,600,"SU-DO-KU");
    readsudoku();
    print_ans();
    fill(a,ans,BLACK);
    printf("\nThe Solved Su-do-ku:\n");
    solve_sudoku(0);
    getch();
}
示例#8
0
int main(int argc, char** argv)
{
    init_bits();
    init_known(argc-1, argv+1);

    solve_sudoku();
    print_matrix();

    return EXIT_SUCCESS;
}
int main(){
    int i , cas ; 
    scanf("%d",&cas);
    for(int i = 0 ; i<cas;i++){
        read();
        if(0 != i)
            cout << "---" << endl;
        solve_sudoku();
    }
    return 0;
}
示例#10
0
void solve_sudoku(int S[][9], int x, int y){
	if(y == 9){
		if(x == 8){
			printSolution(S);
			exit(0);
		} else {
			solve_sudoku(S, x+1,0);
		}
	} else if(S[x][y] == 0){
		int k = 0;
		for (k = 1; k <=9; k++){
			if(feasible(S,x,y,k)){
				S[x][y] = k;
				solve_sudoku(S, x, y+1);
				S[x][y] = 0;
			}
		}
	} else {
		solve_sudoku(S,x,y+1);
	}
}
示例#11
0
int main() {
  int line_number=0;
  char line[LINE_SIZE];

  FILE *fin = fopen("input.txt", "r");

  while(fgets(line, sizeof line, fin) != NULL) {
    build_sudoku(line, line_number);
    line_number++;
  }

  solve_sudoku(0, 0, sudoku);

  return 0;
}
示例#12
0
int main() {
    int sudoku[9][9];
    if (input_sudoku(sudoku) == 1) {
        return ERROR;
    }
    printf("\nSudoku entered:\n");
    print_sudoku(sudoku);
    if(solve_sudoku(sudoku) == 0) {
        printf("\nSolution:\n");
    }
    else {
        printf("\nInvalid sudoku - unable to solve. Partial result:\n");
    }
    print_sudoku(sudoku);
}
示例#13
0
int main() {
  srand(time(NULL));
  int N = 9;
  std::vector<std::vector<int>> M(N, std::vector<int>(N, 0));
  std::vector<std::vector<bool>> given(N, std::vector<bool>(N, false));
  M[1][5] = 3;
  M[1][7] = 8;
  M[1][8] = 5;
  M[2][2] = 1;
  M[2][4] = 2;
  M[3][3] = 5;
  M[3][5] = 7;
  M[4][2] = 4;
  M[4][6] = 1;
  M[5][1] = 9;
  M[6][0] = 5;
  M[6][7] = 7;
  M[6][8] = 3;
  M[7][2] = 2;
  M[7][4] = 1;
  M[8][4] = 4;

  given[1][5] = true;
  given[1][7] = true;
  given[1][8] = true;
  given[2][2] = true;
  given[2][4] = true;
  given[3][3] = true;
  given[3][5] = true;
  given[4][2] = true;
  given[4][6] = true;
  given[5][1] = true;
  given[6][0] = true;
  given[6][7] = true;
  given[6][8] = true;
  given[7][2] = true;
  given[7][4] = true;
  given[8][4] = true;
  std::cout << "Input sudoku: " << std::endl;
  print_sudoku(M, N);
  solve_sudoku(M, given, N);
  std::cout << "Result sudoku: " << std::endl;
  print_sudoku(M, N);
  return 0;
}
示例#14
0
/**
 * This program tries to resolve a given Sudoku file.
 *
 * @param argc Argument count
 * @param argv Arguments
 */
int main(int argc, char** argv) {
    if (argc != 2) {
        printf("Usage: <solver> <sudoku file>\n");
        exit(EXIT_FAILURE);
    } else {
        int ret;

        // allocate matrix to read into
        char** sudoku_array = allocate_sudoku();

        // read input sudoku file
        ret = readSudoku(argv[1], sudoku_array);

        // abort if file is corrupt
        if (ret != 0) {
            printf("The read process failed - exiting\n");
            exit(EXIT_FAILURE);
        }

        // print input sudoku
        printf("<<INPUT  SUDOKU>>\n");
        print_sudoku(sudoku_array);
        printf("-----------------\n");

        // solve it
        ret = solve_sudoku(sudoku_array);

        // print output sudoku
        printf("<<OUTPUT SUDOKU>>\n");
        print_sudoku(sudoku_array);
        printf("-----------------\n");

        // print if the sudoku could be solved
        if (ret == 0)
            printf("The Sodoku was solved\n");
        else
            printf("The Sudoku is irresolvable\n");

        // free allocated matrix
        unallocate_sudoku(sudoku_array);

        exit(EXIT_SUCCESS);
    }
}
int main(){
    int cas = 0;
    char ch[10];
    while(scanf("%s",ch)!=EOF){
        cas ++;
        if(1 != cas)
            cout << endl;
        sudoku[0][0] = turn(ch);
        for(int i = 0 ; i < 9; i++)
            for(int f = 0; f < 9; f++){
                if(0 == i+f)
                    continue;
                scanf("%s",ch);
                sudoku[i][f] = turn(ch);
            }
        solve_sudoku();
    }
    return 0;
}
示例#16
0
int solve_sudoku(int sudoku[9][9], const int guess_in_progress) {
    int i, j, guess, solution[9][9], temp_sudoku[9][9];
    int success_status = 0;

    copy_sudoku(solution, sudoku);
    do {
        copy_sudoku(temp_sudoku, solution);
        for(i = 0; i < 9; ++i) {
            for(j = 0; j < 9; ++j) {
                if(solution[i][j] == 0) {
                    solution[i][j] = solve_at_xy(solution, i, j);
                }
            }
        }
    } while (match_sudoku(solution, temp_sudoku) != 0);

    for(i = 0; i < 9; ++i) {
        for(j = 0; j < 9; ++j) {
            if(solution[i][j] == 0) {
                if(guess_in_progress == TRUE) {
                    return ERROR;
                }
                success_status = 1;
                for(guess = 1; guess <= 9; ++guess) {
                    if (check_conflict(solution, guess, i, j)) {
                        continue;
                    }
                    copy_sudoku(temp_sudoku, solution);
                    temp_sudoku[i][j] = guess;
                    if (solve_sudoku(temp_sudoku, TRUE) != 0) {
                        continue;
                    }
                    copy_sudoku(solution, temp_sudoku);
                    success_status = 0;
                }
            }
        }
    }
    copy_sudoku(sudoku, solution);
    return success_status;
}
示例#17
0
int solve_sudoku(int Board[SIZE][SIZE])
{
	int row, col, num;
	for(row=0; row<SIZE; ++row) {
		for(col=0; col<SIZE; ++col) {
			if(Board[row][col] == 0) {
				for(num=1; num<=9; ++num) {
					if(isSafe(Board, row, col, num)) {
						Board[row][col] = num;
						if(solve_sudoku(Board) == -1) {
							Board[row][col] = 0;
						}
						else {
							break;
						}
					}
				}
				if(Board[row][col] == 0) {
					return -1;
				}
			}	
		}
	}
}
示例#18
0
int main(int argc, char *argv[])
{
  int done;
  char *current_status;

  if (argc == 2)
    read_from_file(argv[1]);

  initscr();
  noecho();
  keypad(stdscr, TRUE);

  current_status = NULL;
  done = 0;
  while (! done) {
    display_update(current_status);

    switch (getch()) {
    case KEY_LEFT:
      current_x--;
      if (current_x < 0)
        current_x = 0;
      break;

    case KEY_RIGHT:
      current_x++;
      if (current_x >= 9)
        current_x = 8;
      break;

    case KEY_UP:
      current_y--;
      if (current_y < 0)
        current_y = 0;
      break;

    case KEY_DOWN:
      current_y++;
      if (current_y >= 9)
        current_y = 8;
      break;

    case '1':
      sudoku[current_y][current_x] = 1;
      break;

    case '2':
      sudoku[current_y][current_x] = 2;
      break;

    case '3':
      sudoku[current_y][current_x] = 3;
      break;

    case '4':
      sudoku[current_y][current_x] = 4;
      break;

    case '5':
      sudoku[current_y][current_x] = 5;
      break;

    case '6':
      sudoku[current_y][current_x] = 6;
      break;

    case '7':
      sudoku[current_y][current_x] = 7;
      break;

    case '8':
      sudoku[current_y][current_x] = 8;
      break;

    case '9':
      sudoku[current_y][current_x] = 9;
      break;

    case '0':
    case ' ':
      sudoku[current_y][current_x] = 0;
      break;

    case KEY_ENTER:
    case '\n':
      if (solve_sudoku())
        current_status = "Unable to solve, enter more numbers.";
      else
        current_status = "Solved!";
      break;

    case 'q':
    case 'Q':
    case '\e':
      done = 1;
      break;

    default:
      break;
    }
  }

  endwin();
  return 0;
}
示例#19
0
int main(int argc, char **argv)
{
    int i, rc, bogus, opt, count, solved, unsolved, solncount, explain, first_soln_only;
    int prt_count, prt_num, prt_score, prt_answer, prt_depth, prt_grid, prt_mask, prt_givens, prt;
    char *myname, outbuf[128], mbuf[28];
    static char inbuf[1024];
    Grid *s, *g, *solved_list;
    FILE *solnfile, *rejects;

    /* Get our command name from invoking command line */
    myname = argv[0];

    /* Print sign-on message to console */
    fprintf(stderr, "%s version %s\n", myname, VERSION);

    /* Init */
    solnfile = stdout;
    rejects = stderr;
    count = solved = unsolved = 0;
    explain = rc = bogus = prt_mask = prt_grid = prt_score = prt_depth = prt_answer = prt_count = prt_num = prt_givens = 0;
    first_soln_only = 0;
    *inbuf = 0;

    /* Parse command line options */
    while ((opt = getopt(argc, argv, OPTIONS)) != -1) {
        switch (opt) {
        case '1':
            first_soln_only = 1;		/* only find first soln */
            break;
        case 'a':
            prt_answer = 1;		/* print solution */
            break;
        case 'c':
            prt_count = 1;		/* number solutions */
            break;
        case 'd':
            prt_depth = 1;
            break;
#ifdef EXPLAIN
        case 'e':
            explain = 1;
            break;
#endif
        case 'G':
            prt_grid = 1;
            break;
        case 'g':
            prt_givens = 1;
            break;
        case 'm':
            prt_mask = 1;
            break;
        case 'n':
            prt_num = 1;
            break;
        case 'p':
            strncpy(inbuf, optarg, sizeof(inbuf)-1);
            break;
        case 's':
            prt_score = 1;
            break;
        default:
        case '?':
            usage(myname);
            exit(1);
        }
    }

    /* Set prt flag if we're printing anything at all */
    prt = prt_mask | prt_grid | prt_score | prt_depth | prt_answer | prt_num | prt_givens;

    /* Anything else on the command line is bogus */
    if (argc > optind) {
        fprintf(stderr, "Extraneous args: ");
        for (i = optind; i < argc; i++) {
            fprintf(stderr, "%s ", argv[i]);
        }
        fprintf(stderr, "\n\n");
        usage(myname);
        exit(1);
    }

    if (first_soln_only && prt_score) {
        fprintf(stderr, "Scoring is meaningless when multi-solution mode is disabled.\n");
    }

    init_solve_engine(NULL, solnfile, rejects, first_soln_only, explain);

    while (*inbuf) {

        count += 1;

        if ((solved_list = solve_sudoku(inbuf)) == NULL) {
            fprintf(rejects, "%d: %s invalid puzzle format\n", count, inbuf);
            *inbuf = 0;
            bogus += 1;
            continue;
        }

        if (solved_list->solncount) {
            solved++;
            for (solncount = 0, g = s = solved_list; s; s = s->next) {
                solncount += 1;
                if (prt_num) {
                    char nbuf[32];
                    if (first_soln_only)
                        sprintf(nbuf, "%d: ", count);
                    else
                        sprintf(nbuf, "%d:%d ", count, solncount);
                    fprintf(solnfile, "%-s", nbuf);
                }
                if (solncount > 1 || first_soln_only) g->score = 0;
                if (prt_score) fprintf(solnfile, "score: %-7d ", g->score);
                if (prt_depth) fprintf(solnfile, "depth: %-3d ", g->maxlvl);
                if (prt_answer || prt_grid) format_answer(s, outbuf);
                if (prt_answer) fprintf(solnfile, "%s", outbuf);
                if (prt_mask) fprintf(solnfile, " %s", cvt_to_mask(mbuf, inbuf));
                if (prt_givens) fprintf(solnfile, " %d", g->givens);
                if (prt_grid) print_grid(outbuf, solnfile);
                if (prt) fprintf(solnfile, "\n");
                if (s->next == NULL && prt_count) fprintf(solnfile, "count: %d\n", solncount);
            }
            if (solncount > 1) {
                rc |= 1;
            }
        }
        else {
            unsolved++;
            rc |= 1;
            fprintf(rejects, "%d: %*.*s insoluble\n", count, PUZZLE_CELLS, PUZZLE_CELLS, inbuf);
            diagnostic_grid(solved_list, rejects);
#if defined(DEBUG)
            mypause();
#endif
        }

        free_soln_list(solved_list);

        *inbuf = 0;
    }

    if (prt)
        fprintf(solnfile, "\nPuzzles: %d, Solved: %d, Insoluble: %d, Invalid: %d\n", count, solved, unsolved, bogus);

    return rc;
}