Determine if a 9x9 Sudoku board is valid. A Sudoku board is valid if:
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.
To determine if the Sudoku board is valid:
rows
, cols
, boxes
) to keep track of the digits we have seen in each row, column, and 3x3 box.rows
, cols
, and boxes
arrays.#include <vector>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
vector<vector<bool>> rows(9, vector<bool>(9, false));
vector<vector<bool>> cols(9, vector<bool>(9, false));
vector<vector<bool>> boxes(9, vector<bool>(9, false));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') continue;
int num = board[i][j] - '1'; // convert char to int (0-8)
int boxIndex = (i / 3) * 3 + j / 3;
if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
return false;
}
rows[i][num] = cols[j][num] = boxes[boxIndex][num] = true;
}
}
return true;
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?