private static Sudoku Solve(Sudoku sudoku, ref int functionCallCount) { functionCallCount++; var(row, column) = SudokuInspector.FindFirstEmptyPosition(sudoku); if (row == -1) { return(sudoku); } for (var number = 1; number <= sudoku.FieldDimension; number++) { if (!sudoku.IsNumberValid(row, column, number)) { continue; } sudoku.SetCell(row, column, number); var solution = Solve(sudoku, ref functionCallCount); if (solution != null) { return(solution); } sudoku.ResetCell(row, column); } return(null); }
private static void SolveSudokuAndDisplayResults(string sudokuPath) { PrintHeader(sudokuPath); Sudoku initial; try { initial = SudokuParser.Parse(sudokuPath); } catch (Exception e) { Console.WriteLine(); Console.WriteLine($"Error: {e.Message}"); Console.WriteLine(); return; } var maxDepth = SudokuInspector.CountEmptyCells(initial); PrintSudoku(initial); Console.WriteLine($"Solving puzzle '{sudokuPath}'..."); var(solution, functionCallCount, elapsedTimeInMs) = SudokuSolver.Solve(initial); if (solution != null) { Console.WriteLine("Done! Solution:"); PrintSudoku(solution); Console.WriteLine($"Puzzle '{sudokuPath}' solved in {elapsedTimeInMs:F3}ms."); Console.WriteLine($"Solution found at depth {maxDepth}, in {functionCallCount} function calls."); Console.WriteLine($"Validity check: {(SudokuValidator.Validate(solution) ? "Passed!" : "Failed.")}"); } else { Console.WriteLine("Puzzle could not be solved. Please make sure the puzzle was defined properly."); } Console.WriteLine(); }