Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode: 36. 有效的数独 #81

Open
resse92 opened this issue Jun 4, 2018 · 0 comments
Open

LeetCode: 36. 有效的数独 #81

resse92 opened this issue Jun 4, 2018 · 0 comments

Comments

@resse92
Copy link
Owner

resse92 commented Jun 4, 2018

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        bool used[9];
        // 检查横着和竖着的是否有相同的数字
        for (int i = 0; i < 9; ++i) {
            fill(used, used + 9, false);
            // 竖着的
            for (int j = 0; j < 9; ++j) {
                if (!check(board[i][j], used))
                    return false;
            }
            
            fill(used, used + 9, false);
            // 横着的
            for (int j = 0; j < 9; ++j) {
                if (!check(board[j][i], used))
                    return false;
            }
        }
        
        for (int r = 0; r < 3; ++r) {
            for (int c = 0; c < 3; ++c) {
                fill(used, used + 9, false);
                // 九宫格
                for (int i = r * 3; i < r * 3 + 3; ++i) {
                    for (int j = c * 3; j < c * 3 + 3; ++ j)
                        if (!check(board[i][j], used))
                            return false;
                }
            }
        }
        return true;
    }
    
    bool check(char ch, bool used[9]) {
        if (ch == '.') return true;
        if (used[ch - '1']) return false;
        
        used[ch - '1'] = true;
        return true;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant