Algo-Sim › Matrix & Bit Manipulation
Valid Sudoku
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Decide whether a partly filled 9 × 9 Sudoku breaks a rule. One pass with a seen table per row, column and 3 × 3 box catches the first repeated digit.
Problem
Given a 9 × 9 board where each cell holds a digit 1–9 or . (empty), return true if no row, no column and none of the nine 3 × 3 boxes contains the same digit twice. Only the filled cells are checked: the board need not be solvable.
Constraints
- board is 9 × 9
- Each cell is '1'–'9' or '.'
Edge cases to test
- An empty board is valid
- A repeat inside a 3 × 3 box but not in any row or column
- A valid board that has no solution (still valid)
Follow-up questions
- How do you compute the box index?
(r / 3) * 3 + c / 3maps each cell to one of the 9 boxes.- How do you use less memory?
- Use a 9-bit mask per row, column and box: 27 integers in total, one bit test per cell.
- How would you solve the puzzle?
- Backtracking over empty cells with the same masks, picking the cell with the fewest options first (LC 37).
Solution
Java
public boolean isValidSudoku(char[][] board) {
boolean[][] rows = new boolean[9][9], cols = new boolean[9][9], boxes = new boolean[9][9];
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] == '.') continue;
int d = board[r][c] - '1', b = (r / 3) * 3 + c / 3;
if (rows[r][d] || cols[c][d] || boxes[b][d]) {
return false;
}
rows[r][d] = cols[c][d] = boxes[b][d] = true;
}
}
return true;
}Python
def is_valid_sudoku(board):
rows = [[False] * 9 for _ in range(9)]
cols = [[False] * 9 for _ in range(9)]
boxes = [[False] * 9 for _ in range(9)]
for r in range(9):
for c in range(9):
if board[r][c] == ".":
continue
d, b = int(board[r][c]) - 1, (r // 3) * 3 + c // 3
if rows[r][d] or cols[c][d] or boxes[b][d]:
return False
rows[r][d] = cols[c][d] = boxes[b][d] = True
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>> &board) {
bool rows[9][9] = {}, cols[9][9] = {}, boxes[9][9] = {};
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
if (board[r][c] == '.') {
continue;
}
int d = board[r][c] - '1', b = (r / 3) * 3 + c / 3;
if (rows[r][d] || cols[c][d] || boxes[b][d]) {
return false;
}
rows[r][d] = cols[c][d] = boxes[b][d] = true;
}
}
return true;
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)