DEV Community

Cover image for solved leetcode sudoko problem using Hashmap
deepi907
deepi907

Posted on

solved leetcode sudoko problem using Hashmap

`

  1. class Solution {
    1. public void solveSudoku(char[][] board) {
    2. HashMap> rows = new HashMap<>();
    3. HashMap> cols = new HashMap<>();
    4. 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.

  1. // Initialize hashmaps
  2. for (int i = 0; i < 9; i++) {
  3. rows.put(i, new HashSet<>());
  4. cols.put(i, new HashSet<>());
  5. boxes.put(i, new HashSet<>());
  6. }
  7. // Fill the hashmaps with the existing numbers on the board
  8. for (int r = 0; r < 9; r++) {
  9. for (int c = 0; c < 9; c++) {
  10. char num = board[r][c];
  11. if (num != '.') {
  12. rows.get(r).add(num);
  13. cols.get(c).add(num);
  14. int boxIndex = (r / 3) * 3 + c / 3;
  15. boxes.get(boxIndex).add(num);
  16. }
  17. }
  18. }
  19. // Start solving the puzzle using backtracking
  20. solve(board, rows, cols, boxes, 0, 0);
  21. }
  22. private boolean solve(char[][] board, HashMap> rows, HashMap> cols, HashMap> boxes, int r, int c) {
  23. if (r == 9) return true; // Puzzle solved
  24. if (c == 9) return solve(board, rows, cols, boxes, r + 1, 0);
  25. if (board[r][c] != '.') return solve(board, rows, cols, boxes, r, c + 1);
  26. int boxIndex = (r / 3) * 3 + c / 3;
  27. // Try placing numbers from 1 to 9
  28. for (char num = '1'; num <= '9'; num++) {
  29. if (!rows.get(r).contains(num) && !cols.get(c).contains(num) && !boxes.get(boxIndex).contains(num)) {
  30. // Place the number
  31. board[r][c] = num;
  32. rows.get(r).add(num);
  33. cols.get(c).add(num);
  34. boxes.get(boxIndex).add(num);
  35. // Continue solving with the next empty cell
  36. if (solve(board, rows, cols, boxes, r, c + 1)) return true;
  37. // Backtrack
  38. board[r][c] = '.';
  39. rows.get(r).remove(num);
  40. cols.get(c).remove(num);
  41. boxes.get(boxIndex).remove(num);
  42. }
  43. }
  44. return false; // No valid solution found, backtrack
  45. }
  46. } When backtracking, removing a number from the hashmaps is straightforward and ensures that all constraints are maintained.

Top comments (0)