[LeetCode] 036. Valid Sudoku (Easy) (C++)

來源:互聯網
上載者:User

標籤: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++)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.