
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.
1public class Solution {
2 public bool IsValidSudoku(char[][] board) {
3 bool[,] rows = new bool[9, 9];
4 bool[,] cols = new bool[9, 9];
5 bool[,] boxes = new bool[9, 9];
6
7 for (int r = 0; r < 9; r++) {
8 for (int c = 0; c < 9; c++) {
9 if (board[r][c] == '.')
10 continue;
11 int num = board[r][c] - '1';
12 int boxIndex = (r / 3) * 3 + c / 3;
13
14 if (rows[r, num] || cols[c, num] || boxes[boxIndex, num]) {
15 return false;
16 }
17 rows[r, num] = true;
18 cols[c, num] = true;
19 boxes[boxIndex, num] = true;
20 }
21 }
22 return true;
23 }
24}The C# implementation uses a similar logic to Java and C++, employing multidimensional arrays for efficient checking and marking of seen numbers.
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#include <vector>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int rows[9] = {0}, cols[9] = {0}, boxes[9] = {0};
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] == '.') continue;
int bit = 1 << (board[r][c] - '1');
int boxIndex = (r / 3) * 3 + c / 3;
if ((rows[r] & bit) || (cols[c] & bit) || (boxes[boxIndex] & bit))
return false;
rows[r] |= bit;
cols[c] |= bit;
boxes[boxIndex] |= bit;
}
}
return true;
}
};This C++ bit manipulation approach employs the same methodology as other languages, using integer arithmetic and bit shifts for rapid checks and updates.