`
- class Solution {
- public void solveSudoku(char[][] board) {
- HashMap> rows = new HashMap<>();
- HashMap> cols = new HashMap<>();
- HashMap> boxes = new HashMap<>();
Here three hashmap used that is row,cols,and boxes Now
it will efficiently keep track of which numbers are already used in each row, column, and 3x3 sub-box of the Sudoku board.
Each entry in these hashmaps is a HashSet to store characters representing numbers.
- // Initialize hashmaps
- for (int i = 0; i < 9; i++) {
- rows.put(i, new HashSet<>());
- cols.put(i, new HashSet<>());
- boxes.put(i, new HashSet<>());
- }
- // Fill the hashmaps with the existing numbers on the board
- for (int r = 0; r < 9; r++) {
- for (int c = 0; c < 9; c++) {
- char num = board[r][c];
- if (num != '.') {
- rows.get(r).add(num);
- cols.get(c).add(num);
- int boxIndex = (r / 3) * 3 + c / 3;
- boxes.get(boxIndex).add(num);
- }
- }
- }
- // Start solving the puzzle using backtracking
- solve(board, rows, cols, boxes, 0, 0);
- }
- private boolean solve(char[][] board, HashMap> rows, HashMap> cols, HashMap> boxes, int r, int c) {
- if (r == 9) return true; // Puzzle solved
- if (c == 9) return solve(board, rows, cols, boxes, r + 1, 0);
- if (board[r][c] != '.') return solve(board, rows, cols, boxes, r, c + 1);
- int boxIndex = (r / 3) * 3 + c / 3;
- // Try placing numbers from 1 to 9
- for (char num = '1'; num <= '9'; num++) {
- if (!rows.get(r).contains(num) && !cols.get(c).contains(num) && !boxes.get(boxIndex).contains(num)) {
- // Place the number
- board[r][c] = num;
- rows.get(r).add(num);
- cols.get(c).add(num);
- boxes.get(boxIndex).add(num);
- // Continue solving with the next empty cell
- if (solve(board, rows, cols, boxes, r, c + 1)) return true;
- // Backtrack
- board[r][c] = '.';
- rows.get(r).remove(num);
- cols.get(c).remove(num);
- boxes.get(boxIndex).remove(num);
- }
- }
- return false; // No valid solution found, backtrack
- }
- } When backtracking, removing a number from the hashmaps is straightforward and ensures that all constraints are maintained.
Top comments (0)