
Sponsored
Sponsored
This approach uses hash sets to track the unique numbers found in each row, column, and 3x3 sub-box. We iterate over each cell in the board, and check if the current value has been seen before in the current row, column, or sub-box. If it has, we return false. Otherwise, we add the value to the respective sets.
Time Complexity: O(1) because the board size is constant (9x9).
Space Complexity: O(1) due to the fixed size of additional data structures used.
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6 bool isValidSudoku(vector<vector<char>>& board) {
7 bool rows[9][9] = {false};
8 bool cols[9][9] = {false};
9 bool boxes[9][9] = {false};
10
11 for (int r = 0; r < 9; r++) {
12 for (int c = 0; c < 9; c++) {
13 if (board[r][c] == '.') continue;
14 int num = board[r][c] - '1';
15 int boxIndex = (r / 3) * 3 + c / 3;
16
17 if (rows[r][num] || cols[c][num] || boxes[boxIndex][num]) {
18 return false;
19 }
20 rows[r][num] = true;
21 cols[c][num] = true;
22 boxes[boxIndex][num] = true;
23 }
24 }
25 return true;
26 }
27};This C++ solution is akin to the C and Java solutions, using arrays to keep track of seen digits and validating each digit as we traverse the board.
This approach seeks to replace sets with bit manipulations to compress space usage for tracking seen numbers. We increment bits in an integer representing whether a digit has been seen in rows, columns, or boxes.
Time Complexity: O(1) as the board size and iteration steps remain constant.
Space Complexity: O(1) due to the integer used for tracking positions, which is constant.
1#
The C implementation uses bitwise operations to efficiently track the presence of numbers in various rows, columns, and boxes, leveraging integer manipulation to handle logic checks.