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 44 45
| class Solution { public: bool col[9][9]; bool row[9][9]; bool block[3][3][9]; bool valid; vector<pair<int,int>>spaces;
void dfs(vector<vector<char>>& board, int pos){ if(pos == spaces.size()){ valid = true; return; } int i = spaces[pos].first; int j = spaces[pos].second; for(int t = 1;t <= 9; t++){ if(!row[i][t - 1] && !col[j][t - 1] && !block[i/3][j/3][t-1] && !valid){ board[i][j] = t + '0'; row[i][t - 1] = col[j][t - 1] = block[i/3][j/3][t-1] = true; dfs(board , pos + 1); row[i][t - 1] = col[j][t - 1] = block[i/3][j/3][t-1] = false; }
} } void solveSudoku(vector<vector<char>>& board) { memset(col, false, sizeof(col)); memset(col, false, sizeof(row)); memset(col, false, sizeof(block)); for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ if(board[i][j] == '.'){ auto p = make_pair(i, j); spaces.push_back(p); } else{ row[i][board[i][j] - '0' - 1] = true; col[j][board[i][j] - '0' - 1] = true; block[i/3][j/3][board[i][j] - '0' - 1] = true; } } } dfs(board, 0); } };
|