- Valid Sudoku
Determine whether a Sudoku is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character …
Example
Example 1:
Input:
[“53…7…”,“6…195…”,".98…6.",“8…6…3”,“4…8.3…1”,“7…2…6”,".6…28.","…419…5","…8…79"]
Output: true
Explanation:
The sudoku is look like this. It’s vaild.
Valid Sudoku
Example 2:
Input:
[“53…7j…”,“6…195…”,".98…6.",“8…6…3”,“4…8.3…1”,“7…2…6”,".6…28.","…419…5","…8…79"]
Output: false
Explanation:
The sudoku is look like this. It’s invaild because there are two ‘5’ in the first row and the sixth line.
image
Clarification
What is Sudoku?
http://sudoku.com.au/TheRules.aspx
https://zh.wikipedia.org/wiki/數獨
https://en.wikipedia.org/wiki/Sudoku
http://baike.baidu.com/subview/961/10842669.htm
Notice
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
解法1:
注意:
用gridIndex = (i / 3) * 3 + j / 3得到cell的index
class Solution {
public:
/**
* @param board: the board
* @return: whether the Sudoku is valid
*/
bool isValidSudoku(vector<vector<char>> &board) {
int m = board.size();
int n = board[0].size();
if (m != 9 || n !=9) return false;
unordered_map<char, int> um; //number, count
for (int i = 0; i < 9; ++i) {
um.clear();
for (int j = 0; j < 9; ++j) {
if (board[i][j] >= '0' && board[i][j] <= '9' && um[board[i][j]]++ > 0) {
return false;
}
}
// if (um.size() != 9) return false;
}
for (int i = 0; i < 9; ++i) {
um.clear();
for (int j = 0; j < 9; ++j) {
if (board[j][i] >= '0' && board[j][i] <= '9' && um[board[j][i]]++ > 0) {
return false;
}
}
// if (um.size() != 9) return false;
}
vector<unordered_set<int>> gridArray(9); //gridIndex, number
for (int i = 0; i < 9; ++i) {
//um.clear();
for (int j = 0; j < 9; ++j) {
int gridIndex = (i / 3) * 3 + j / 3; // the x-th small grid
if (board[i][j] >= '0' && board[i][j] <= '9' && gridArray[gridIndex].find(board[i][j]) != gridArray[gridIndex].end())) {
return false;
} else {
gridArray[gridIndex].insert(board[i][j]);
}
}
// if (um.size() != 9) return false;
}
return true;
}
};
解法2:
把解法1的三个步骤放到一起,不过要用3个2D vector。
class Solution {
public:
/**
* @param board: the board
* @return: whether the Sudoku is valid
*/
bool isValidSudoku(vector<vector<char>> &board) {
int m = board.size();
int n = board[0].size();
if (m != 9 || n !=9) return false;
vector<vector<bool>> rowsFlag(9, vector<bool>(9));
vector<vector<bool>> colsFlag(9, vector<bool>(9));
vector<vector<bool>> cellsFlag(9, vector<bool>(9));
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') continue;
int cellIndex = (i / 3) * 3 + j / 3; // the x-th small grid
int num = board[i][j] - '1';
if (rowsFlag[i][num] || colsFlag[j][num] || cellsFlag[cellIndex][num]) return false;
rowsFlag[i][num] = true;
colsFlag[j][num] = true;
cellsFlag[cellIndex][num] = true;
}
}
return true;
}
};
本文介绍了一种算法,用于验证一个部分填充的数独是否有效。通过检查每一行、每一列以及每一个九宫格内数字是否重复,确保数独遵循基本规则。提供了两种解法,一种使用哈希表,另一种使用位标记。
1011

被折叠的 条评论
为什么被折叠?



