首页 > 代码库 > LeetCode "Sudoku Solver"
LeetCode "Sudoku Solver"
Simply DFS + Backtrace, as N-Queen
class Solution {public: vector<unordered_set<char>> rows; vector<unordered_set<char>> cols; vector<vector<unordered_set<char>>> subboxHm; bool isValid(char c, int i, int j) { return (rows[j].find(c) == rows[j].end() && cols[i].find(c) == cols[i].end() && subboxHm[j/3][i/3].find(c) == subboxHm[j/3][i/3].end()); } void putRecord(char c, int i, int j, vector<vector<char> > &board) { board[j][i] = c; rows[j].insert(c); cols[i].insert(c); subboxHm[j/3][i/3].insert(c); } void clearRecord(char c, int i, int j, vector<vector<char> > &board) { board[j][i] = ‘.‘; rows[j].erase(c); cols[i].erase(c); subboxHm[j/3][i/3].erase(c); } bool goDFS(vector<vector<char> > &board) { size_t cnt = board.size(); for(int j = 0; j < cnt; j ++) for(int i = 0; i < cnt; i ++) { char c = board[j][i]; if (c == ‘.‘) { for(char c = ‘1‘; c <= ‘9‘; c ++) { if(isValid(c, i, j)) { putRecord(c, i, j, board); if(goDFS(board)) return true; else clearRecord(c, i, j, board); } } return false; } } return true; } void solveSudoku(vector<vector<char> > &board) { size_t cnt = board.size(); // Init rows.resize(cnt); cols.resize(cnt); subboxHm.resize(cnt/3); for(int i = 0; i < cnt/3; i ++) subboxHm[i].resize(cnt/3); // Fill in original record for(int j = 0; j < cnt; j ++) for(int i = 0; i < cnt; i ++) { char c = board[j][i]; if (c != ‘.‘) { rows[j].insert(c); cols[i].insert(c); unordered_set<char> &sb = subboxHm[j/3][i/3]; sb.insert(c); } } goDFS(board); }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。