public void SolveSudoku(char[][] board) { var placeHoldersCount = 0; var placeHolders = new bool[9][]; var numberStatuses = new NumberStatus[9]; for (int i = 0; i < 9; i++) { numberStatuses[i] = new NumberStatus(); } for (int i = 0; i < 9; i++) { placeHolders[i] = new bool[9]; for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { placeHoldersCount++; placeHolders[i][j] = true; } else { int val = board[i][j] - '1'; numberStatuses[val].UsedInColumns[j] = true; numberStatuses[val].UsedInRows[i] = true; numberStatuses[val].UsedInSquares[NumberStatus.GetSquareNumber(i, j)] = true; } } } SolveSudokuImpl(board, placeHolders, numberStatuses, placeHoldersCount); }
private bool SolveSudokuImpl(char[][] board, bool[][] placeHolders, NumberStatus[] numberStatus, int numbersLeft) { if (numbersLeft == 0) { return(CheckSudokuSolved(board)); } for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (!placeHolders[i][j] || board[i][j] != '.') { continue; } for (char c = '1'; c <= '9'; c++) { var val = c - '1'; if (numberStatus[val].UsedInRows[i] || numberStatus[val].UsedInColumns[j] || numberStatus[val].UsedInSquares[NumberStatus.GetSquareNumber(i, j)]) { continue; } var prevUsedInRows = numberStatus[val].UsedInRows[i]; var prevUsedInColumns = numberStatus[val].UsedInColumns[j]; var prevUsedInSquares = numberStatus[val].UsedInSquares[NumberStatus.GetSquareNumber(i, j)]; board[i][j] = c; if (SolveSudokuImpl(board, placeHolders, numberStatus, numbersLeft - 1)) { return(true); } board[i][j] = '.'; numberStatus[val].UsedInRows[i] = prevUsedInRows; numberStatus[val].UsedInColumns[j] = prevUsedInColumns; numberStatus[val].UsedInSquares[NumberStatus.GetSquareNumber(i, j)] = prevUsedInSquares; } } } return(false); }