leetcode 36. Valid Sudoku
2018-01-12 18:52
453 查看
啊,我还以为求数独呢,原来是求当前的是否符合数独的规范。。
那就横、竖、小九宫格分别判断是否有相同的呗。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_map<char, bool> row, col, all;
for (int i = 0; i < 9; ++i) {
col.clear();
for (int j = 0; j < 9; ++j) {
char ch = board[j][i];
if (ch == '.')
continue;
if (col.find(ch) != col.end())
return false;
else
col.insert({ch, true});
}
}
for (int i = 0; i < 9; ++i) {
row.clear();
for (int j = 0; j < 9; ++j) {
char ch = board[i][j];
if (ch == '.')
continue;
if (row.find(ch) != row.end())
return false;
else
row.insert({ch, true});
}
}
for (int i = 0; i < 8; i += 3) {
for (int j = 0; j < 8; j += 3) {
all.clear();
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
char ch = board[i + k][j + l];
if (ch == '.')
continue;
if (all.find(ch) != all.end())
return false;
else
all.insert({ch, true});
}
}
}
}
return true;
}
};
那就横、竖、小九宫格分别判断是否有相同的呗。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_map<char, bool> row, col, all;
for (int i = 0; i < 9; ++i) {
col.clear();
for (int j = 0; j < 9; ++j) {
char ch = board[j][i];
if (ch == '.')
continue;
if (col.find(ch) != col.end())
return false;
else
col.insert({ch, true});
}
}
for (int i = 0; i < 9; ++i) {
row.clear();
for (int j = 0; j < 9; ++j) {
char ch = board[i][j];
if (ch == '.')
continue;
if (row.find(ch) != row.end())
return false;
else
row.insert({ch, true});
}
}
for (int i = 0; i < 8; i += 3) {
for (int j = 0; j < 8; j += 3) {
all.clear();
for (int k = 0; k < 3; ++k) {
for (int l = 0; l < 3; ++l) {
char ch = board[i + k][j + l];
if (ch == '.')
continue;
if (all.find(ch) != all.end())
return false;
else
all.insert({ch, true});
}
}
}
}
return true;
}
};
相关文章推荐
- LeetCode(36)--Valid Sudoku
- leetcode-36. Valid Sudoku
- leetcode-36 Valid Sudoku
- [Leetcode] 36. Valid Sudoku
- Leetcode 36 Valid Sudoku 数独的合法性判断
- Leetcode 36 Valid Sudoku
- LeetCode(36)Valid Sudoku
- LeetCode 36. Valid Sudoku(数独Ⅰ)
- 【C++】【LeetCode】36. Valid Sudoku
- Leetcode -- 36. Valid Sudoku
- LeetCode解题笔记36 Valid Sudoku
- leetcode 36. Valid Sudoku
- leetcode 36. Valid Sudoku
- [leetcode 36] Valid Sudoku
- 36 leetcode - Valid Sudoku
- [leetcode 36] Valid Sudoku
- LeetCode-36-Valid Sudoku(模拟/遍历)-Easy
- LeetCode(36)Valid Sudoku
- leetcode 36. Valid Sudoku
- [LeetCode] 36. Valid Sudoku