Leetcode 36. Valid Sudoku

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Valid Sudoku
Valid Sudoku

2. Solution

class Solution {
public:
    bool isValidSudoku(vector>& board) {
        return validate(board);
    }
    
private:
    bool validate(vector>& board) {
        int n = board.size();
        vector>> subboxes(3, vector>(3));
        for(int i = 0; i < n; i++) {
            unordered_map row;
            unordered_map column;
            for(int j = 0; j < n; j++) {
                if(board[i][j] != '.') {
                    if(row.find(board[i][j]) != row.end()) {
                        return false;
                    }
                    else {
                        row[board[i][j]] = board[i][j];
                    }
                    if(subboxes[i / 3][j / 3].find(board[i][j]) != row.end()) {
                        return false;
                    }
                    else {
                        subboxes[i / 3][j / 3][board[i][j]] = board[i][j];
                    }
                }
                if(board[j][i] != '.') {
                    if(column.find(board[j][i]) != column.end()) {
                        return false;
                    }
                    else {
                        column[board[j][i]] = board[j][i];
                    }
                }
            }
        }
        return true;
    }
};

Reference

  1. https://leetcode.com/problems/valid-sudoku/description/

你可能感兴趣的:(Leetcode 36. Valid Sudoku)