37.sudoku-solver.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. class Solution {
  2. private char[][] board;
  3. private int[] row;
  4. private int[] col;
  5. private int[] box;
  6. public void solveSudoku(char[][] board) {
  7. this.board = board;
  8. row = new int[9];
  9. col = new int[9];
  10. box = new int[9];
  11. for (int i = 0; i < 9; i++) {
  12. for (int j = 0; j < 9; j++) {
  13. char c;
  14. if ((c = board[i][j]) == '.') continue;
  15. set(i, j, c - '0');
  16. }
  17. }
  18. dfs(0, 0);
  19. }
  20. private boolean dfs(int y, int x) {
  21. for (; y < 9; y++) {
  22. for (x = x == 9 ? 0 : x; x < 9; x++) {
  23. char c;
  24. if ((c = board[y][x]) != '.') continue;
  25. int i = 1;
  26. for (; i <= 9; i++) {
  27. if (!set(y, x, i)) continue;
  28. if (dfs(y, x)) return true;
  29. unset(y, x);
  30. }
  31. if (i == 10) return false;
  32. }
  33. }
  34. return true;
  35. }
  36. private boolean set(int y, int x, int val) {
  37. int mask = 1 << val;
  38. int id = y / 3 * 3 + x / 3;
  39. if ((row[y] & mask) != 0 || (col[x] & mask) != 0 || (box[id] & mask) != 0) return false;
  40. row[y] |= mask;
  41. col[x] |= mask;
  42. box[id] |= mask;
  43. board[y][x] = (char)(val + '0');
  44. return true;
  45. }
  46. private void unset(int y, int x) {
  47. int val = board[y][x] - '0';
  48. int mask = (0x400 - 1) ^ (1 << val);
  49. int id = y / 3 * 3 + x / 3;
  50. row[y] &= mask;
  51. col[x] &= mask;
  52. box[id] &= mask;
  53. board[y][x] = '.';
  54. }
  55. }