How to Generate a -complete- sudoku board? algorithm error

前端 未结 6 1198
情话喂你
情话喂你 2020-12-31 17:35

I\'m trying to generate a complete (ie, each cell filled with a number) Sudoku-like board. It\'s for something else that has nothing to do with sudokus, so I am not interest

6条回答
  •  Happy的楠姐
    2020-12-31 18:24

    You have at least few ways to do that, but usually you will need recurrence / backtracking. It would be great to have the solver also, just to check if partly filled puzzle has solution (and the unique one - for stoping criteria - if you want the real sudoku).

    While performing backtracking / recurrence you will need:

    • to randomly select available empty cell (you can optimize this step by measuring digidts still free on the given cell, and then sorting)

    • to randomly select still available digit in that cell

    • you fill the cell and check if the solution exists, if yes - go further, if not - perform the step back.

    Starting points: - starting with completely empty puzzle - starting with partially filled puzzle - starting with solved puzzle (there are a lot of transformations not changing the solution existence, but making the puzzle different - i.e.: reflection, rotation, transposition, segment swapping, columns / rows swapping within segments, permutation, etc.)

    I was recently using the Janet Sudoku library which provides solver, generator and puzzle transformation methods.

    Janet Sudoku website

    Please refer to the below source codes available on the GitHub

    Sudoku Solver

    Sudoku Generator

    Sudoku Transformations

    Library usage is pretty simple, ie:

    SudokuGenerator g = new SudokuGenerator();
    int[][] puzzle = g.generate();
    SudokuSolver s = new SudokuSolver(puzzle);
    s.solve();
    int[][] solvedPuzzle = s.getSolvedBoard();
    

    Best regards,

提交回复
热议问题