Leetcode 36. Valid Sudoku

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83450552

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

1. Description

Valid Sudoku

Valid Sudoku

2. Solution

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        return validate(board);
    }
    
private:
    bool validate(vector<vector<char>>& board) {
        int n = board.size();
        vector<vector<unordered_map<char, char>>> subboxes(3, vector<unordered_map<char, char>>(3));
        for(int i = 0; i < n; i++) {
            unordered_map<char, char> row;
            unordered_map<char, char> 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/
阅读更多

扫码向博主提问

SnailTyan

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • 深度学习
  • PyTorch
  • OCR
  • Docker
  • Caffe
去开通我的Chat快问

没有更多推荐了,返回首页