Leetcode 36. Valid Sudoku

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

1. Description

Valid Sudoku

Valid Sudoku

2. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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/
如果有收获,可以请我喝杯咖啡!