[leetcode] 36. Valid Sudoku 解题报告

来源:互联网 发布:北京正规排名优化企业 编辑:程序博客网 时间:2024/06/05 04:39

题目链接:https://leetcode.com/problems/valid-sudoku/

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.


A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.


思路:一个合法的数独不一定是可解的, 因此我们只需要判断是不是给的方格合法就行了, 也就是没有在同一列, 同一行, 或者一个9宫格出现相同的数. 一个十分简便的方法是用位运算的方式, 记录每一行,每 一列, 每一个九宫格的字符相与的结果就一个数保存. 这样如果在某一行列或者宫出现了相同的数的时候我们可以根据并的结果得知. 如果出现了重复的数字则是非法的, 如果到最后仍然找不大重复的数字, 那就是一个合法的数独.

class Solution {public:    bool isValidSudoku(vector<vector<char>>& board) {        int m = board.size(), n = board[0].size();        vector<int> row(9, 0), col(9, 0), squire(9, 0);        for(int i =0; i < m; i++)        {            for(int j =0; j < n; j++)            {                if(board[i][j] == '.') continue;                int val = 1<<(board[i][j]-'0');                if((row[i]&val) || (col[j]&val) || (squire[i/3*3+j/3]&val)) return false;                row[i] |= val, col[j] |= val, squire[i/3*3+j/3] |= val;            }        }        return true;    }};
参考: https://leetcode.com/discuss/92445/yet-another-java-2ms-solution

0 0
原创粉丝点击