static SudokuPuzzle SolvePuzzle(SudokuPuzzle puzzle, int startRow, int startColumn) { // 开始解谜题 while (true) { // 如果谜题解开,直接跳过 if (puzzle.IsSolved) { break; } int j = startColumn; for (int i = startRow; i < 9; i++) { for (; j < 9; j++) { if (puzzle.Item[i][j].IsConfirmed) { continue; } List <int> possibleVals = puzzle.Item[i][j].GetPossibleVals(); for (int k = 0; k < possibleVals.Count; k++) { puzzle.Item[i][j].IsConfirmed = true; puzzle.Item[i][j].Val = possibleVals[k]; puzzle.PrintPuzzle(); if (!CheckPuzzle(puzzle)) { puzzle.Item[i][j].IsConfirmed = false; puzzle.Item[i][j].Val = 0; puzzle.PrintPuzzle(); if (k == possibleVals.Count - 1) { return(puzzle); } continue; } int nextRow = startRow; int nextColumn = startColumn + 1; if (nextColumn >= 9) { nextRow = nextRow + 1; nextColumn = 0; } if (nextRow < 9) { puzzle = SolvePuzzle(puzzle, nextRow, nextColumn); } } } j = 0; } } return(puzzle); }
static SudokuPuzzle SolvePuzzle(SudokuPuzzle puzzle, int startRow, int startColumn) { // 开始解谜题 while (true) { if (puzzle.IsSolved) break; int j = startColumn; for (int i = startRow; i < 9; i++) { for (; j < 9; j++) { if (puzzle.Item[i][j].IsConfirmed) continue; List<int> possibleVals = puzzle.Item[i][j].GetPossibleVals(); for (int k = 0; k < possibleVals.Count; k++) { puzzle.Item[i][j].IsConfirmed = true; puzzle.Item[i][j].Val = possibleVals[k]; puzzle.PrintPuzzle(); if (!CheckPuzzle(puzzle)) { puzzle.Item[i][j].IsConfirmed = false; puzzle.Item[i][j].Val = 0; puzzle.PrintPuzzle(); if (k == possibleVals.Count - 1) return puzzle; continue; } int nextRow = startRow; int nextColumn = startColumn + 1; if (nextColumn >= 9) { nextRow = nextRow + 1; nextColumn = 0; } if (nextRow < 9) { puzzle = SolvePuzzle(puzzle, nextRow, nextColumn); } } } j = 0; } } return puzzle; }