标签:style blog color io for ar div amp
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); } };
LeetCode "Sudoku Solver",布布扣,bubuko.com
标签:style blog color io for ar div amp
原文地址:http://www.cnblogs.com/tonix/p/3915954.html