標籤:c++ leetcode 演算法
索引:[LeetCode] Leetcode 題解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
036. Valid Sudoku (Easy)
連結:
題目:https://leetcode.com/problems/valid-sudoku/
代碼(github):https://github.com/illuz/leetcode
題意:
判斷一個數獨是否有效。
有效數獨不強求有解。
分析:
只要同一行、列、塊裡沒有相同數字就行了。
開個數組記錄就行了,沒什麼難度,可以用二進位來表示,表位元運算加速。
(注意是判斷有效,不是有解,我剛開始給求解了,TLE 了好多次。。。)
代碼:
C++:
class Solution {private:int row[9], col[9], sqr[3][3];bool check(int x, int y, int val) {return !((row[x]>>val)&1) && !((col[y]>>val)&1) && !((sqr[x/3][y/3]>>val)&1);}void mark(int x, int y, int val) {row[x] |= (1<<val);col[y] |= (1<<val);sqr[x/3][y/3] |= (1<<val);}<pre name="code" class="java">//求解 Sudoku
//void unmark(int x, int y, int val) {//row[x] -= (1<<val);//col[y] -= (1<<val);//sqr[x/3][y/3] -= (1<<val);//}//bool dfs(int pos, vector<vector<char> > &board) {//// x = pos / 9, y = pos % 9//if (pos == 81)//return true;//if (board[pos/9][pos%9] != '.') {//return dfs(pos + 1, board);//} else {//for (int i = 0; i < 9; i++)//if (check(pos/9, pos%9, i)) {//mark(pos/9, pos%9, i);//if (dfs(pos + 1, board))//return true;//unmark(pos/9, pos%9, i);//}//}//return false;//}public: bool isValidSudoku(vector<vector<char> > &board) {memset(row, 0, sizeof(row));memset(col, 0, sizeof(col));memset(sqr, 0, sizeof(sqr));for (int i = 0; i < board.size(); i++)for (int j = 0; j < board[i].size(); j++)if (board[i][j] != '.') {if (!check(i, j, board[i][j] - '1'))return false;mark(i, j, board[i][j] - '1');}return true;// return dfs(0, board); }};
[LeetCode] 036. Valid Sudoku (Easy) (C++)