1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class Solution { public: void solveSudoku(vector<vector<char>>& board) { solveSudoku1(board, 0, 0); } bool solveSudoku1(vector<vector<char>>& board, int i, int j) { if (i>=9||j>=9) return true; if (board[i][j]=='.') { vector<bool> used_numbers(9); for (int k=0;k<9;k++) { if (board[i][k]!='.') { used_numbers[board[i][k]-'1']=true; } } for (int k=0;k<9;k++) { if (board[k][j]!='.') { used_numbers[board[k][j]-'1']=true; } } int grid_i = i / 3; int grid_j = j / 3; for (int m=3*grid_i;m<3+3*grid_i;m++) { for (int n=3*grid_j;n<3+3*grid_j;n++) { if (board[m][n]!='.') { used_numbers[board[m][n]-'1']=true; } } } for (int ii=0;ii<9;ii++) { if (used_numbers[ii]==false) { board[i][j] = ii+'1'; if (solveSudoku1(board, i+(j+1)/9, (j+1)%9)) { return true; } } } board[i][j] = '.'; return false; }else{ return solveSudoku1(board, i+(j+1)/9, (j+1)%9); } } };
|