public bool TryAndSolveOnce(SudokuGrid inputGrid) { while (inputGrid.FindAllEmptySquares().Count != 0) { bool hasASquareBeenFilled = false; foreach (var emptySquare in inputGrid.FindAllEmptySquares()) { List <int> validOptionsForSquare = DetermineValidOptionsForSquare(emptySquare, inputGrid); if (validOptionsForSquare.Count == 0) { return(false); } if (validOptionsForSquare.Count == 1) { inputGrid.FillInSquare(emptySquare, validOptionsForSquare[0]); hasASquareBeenFilled = true; } } if (!hasASquareBeenFilled) { return(true); } } return(true); }
public bool TryAndSolveOnce(SudokuGrid inputGrid) { while (inputGrid.FindAllEmptySquares().Count != 0) { bool hasASquareBeenFilled = false; foreach (var emptySquare in inputGrid.FindAllEmptySquares()) { List<int> validOptionsForSquare = DetermineValidOptionsForSquare(emptySquare, inputGrid); if (validOptionsForSquare.Count == 0) { return false; } if (validOptionsForSquare.Count == 1) { inputGrid.FillInSquare(emptySquare, validOptionsForSquare[0]); hasASquareBeenFilled = true; } } if (!hasASquareBeenFilled) { return true; } } return true; }
public SudokuGrid Solve(SudokuGrid inputGrid) { bool returnFromOneSolve = TryAndSolveOnce(inputGrid); if (!returnFromOneSolve) { return(null); } if (inputGrid.FindAllEmptySquares().Count != 0) { Console.WriteLine("Solving failed at this step"); } return(inputGrid); }
public SudokuGrid Solve(SudokuGrid inputGrid) { bool returnFromOneSolve = TryAndSolveOnce(inputGrid); if (!returnFromOneSolve) { return null; } if (inputGrid.FindAllEmptySquares().Count != 0) { Console.WriteLine("Solving failed at this step"); } return inputGrid; }
private ImmutableSudokuGrid Solve(ImmutableSudokuGrid grid, SudokuSolver simpleSolver, bool isRandomSolve, int disallowedValue, int disallowedRow, int disallowedColumn) { SudokuGrid mutableGrid = grid.MakeMutableCopy(); bool isGridValid = simpleSolver.TryAndSolveOnce(mutableGrid); grid = new ImmutableSudokuGrid(mutableGrid.Elements); if (!isGridValid) { return(null); } var emptySquareList = grid.FindAllEmptySquares(); if (emptySquareList.Count == 0) { return(grid); } SquareCoordinate emptySquareToFill = emptySquareList[0]; if (isRandomSolve) { var randomEmptySquare = new Random().Next(emptySquareList.Count - 1); emptySquareToFill = emptySquareList[randomEmptySquare]; } var validOptions = simpleSolver.DetermineValidOptionsForSquare(emptySquareToFill, grid); if (emptySquareToFill.Row == disallowedRow && emptySquareToFill.Column == disallowedColumn && disallowedValue != 0) { validOptions.Remove(disallowedValue); } for (int i = 0; i < validOptions.Count; i++) { ImmutableSudokuGrid solvedGrid = Solve(grid.WithExtraSquare(emptySquareToFill, validOptions[i]), isRandomSolve); if (solvedGrid != null) { return(solvedGrid); } } return(null); }