Skip to content

LeetCode: 36. 有效的数独 #81

Open

Description

@resse92
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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions