|
| 1 | +package Backtracking; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +public class sudokuSolverUsingCharsArrays { |
| 6 | + public static void main(String[] args) { |
| 7 | + char[][] charArray = { |
| 8 | + {'5', '3', '.', '.', '7', '.', '.', '.', '.'}, |
| 9 | + {'6', '.', '.', '1', '9', '5', '.', '.', '.'}, |
| 10 | + {'.', '9', '8', '.', '.', '.', '.', '6', '.'}, |
| 11 | + {'8', '.', '.', '.', '6', '.', '.', '.', '3'}, |
| 12 | + {'4', '.', '.', '8', '.', '3', '.', '.', '1'}, |
| 13 | + {'7', '.', '.', '.', '2', '.', '.', '.', '6'}, |
| 14 | + {'.', '6', '.', '.', '.', '.', '2', '8', '.'}, |
| 15 | + {'.', '.', '.', '4', '1', '9', '.', '.', '5'}, |
| 16 | + {'.', '.', '.', '.', '8', '.', '.', '7', '9'} |
| 17 | + }; |
| 18 | + solveSudoku(charArray); |
| 19 | + System.out.println(Arrays.deepToString(charArray)); |
| 20 | + } |
| 21 | + |
| 22 | + public static void solveSudoku(char[][] board) { |
| 23 | + int[] complete = new int[1]; |
| 24 | + solver(board, 0, 0, complete); |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | + public static void solver(char[][] board, int row, int col, int[] complete) { |
| 29 | + if (row == board.length - 1 && col == board[0].length) { |
| 30 | + complete[0] = 1; |
| 31 | + return; |
| 32 | + } |
| 33 | + if (col == board[0].length) { |
| 34 | + solver(board, row + 1, 0, complete); |
| 35 | + return; |
| 36 | + } |
| 37 | + if (board[row][col] == '.') { |
| 38 | + for (int i = 1; i <= 9; i++) { |
| 39 | + if (isSafe(board, row, col, (char) (i + '0'))) { |
| 40 | + board[row][col] = (char) (i + '0'); |
| 41 | + solver(board, row, col + 1, complete); |
| 42 | + if (complete[0] != 1) { |
| 43 | + board[row][col] = '.'; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } else { |
| 48 | + solver(board, row, col + 1, complete); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private static boolean isSafe(char[][] board, int row, int col, char ch) { |
| 53 | + // check the row |
| 54 | + //row |
| 55 | + for (int i = 0; i < 9; i++) { |
| 56 | + if (board[i][col] == ch) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + } |
| 60 | + //col |
| 61 | + for (int i = 0; i < 9; i++) { |
| 62 | + if (board[row][i] == ch) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + int sqrt = (int) (Math.sqrt(board.length)); |
| 68 | + int rowStart = row - row % sqrt; |
| 69 | + int colStart = col - col % sqrt; |
| 70 | + |
| 71 | + for (int r = rowStart; r < rowStart + sqrt; r++) { |
| 72 | + for (int c = colStart; c < colStart + sqrt; c++) { |
| 73 | + if (board[r][c] == ch) { |
| 74 | + return false; |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + return true; |
| 79 | + } |
| 80 | +} |
0 commit comments