|
| 1 | +package backtracking; |
| 2 | + |
| 3 | +public class Sudoku_Solver { |
| 4 | + |
| 5 | + static int N = 9; |
| 6 | + |
| 7 | + static boolean solveSudoku(int grid[][], int row, int col) { |
| 8 | + if (row == N - 1 && col == N) |
| 9 | + return true; |
| 10 | + |
| 11 | + if (col == N) { |
| 12 | + row++; |
| 13 | + col = 0; |
| 14 | + } |
| 15 | + |
| 16 | + if (grid[row][col] != 0) |
| 17 | + return solveSudoku(grid, row, col + 1); |
| 18 | + |
| 19 | + for (int num = 1; num < 10; num++) { |
| 20 | + |
| 21 | + if (isSafe(grid, row, col, num)) { |
| 22 | + |
| 23 | + grid[row][col] = num; |
| 24 | + if (solveSudoku(grid, row, col + 1)) |
| 25 | + return true; |
| 26 | + } |
| 27 | + grid[row][col] = 0; |
| 28 | + } |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + static void print(int[][] grid) { |
| 33 | + for (int i = 0; i < N; i++) { |
| 34 | + for (int j = 0; j < N; j++) |
| 35 | + System.out.println(grid[i][j] + " "); |
| 36 | + System.err.println(); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + static boolean isSafe(int[][] grid, int row, int col, int num) { |
| 41 | + for (int x = 0; x <= 8; x++) { |
| 42 | + if (grid[row][x] == num) |
| 43 | + return false; |
| 44 | + } |
| 45 | + |
| 46 | + for (int x = 0; x <= 8; x++) { |
| 47 | + if (grid[x][col] == num) |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + int startRow = row - row % 3, startCol = col - col % 3; |
| 52 | + for (int i = 0; i < 3; i++) { |
| 53 | + for (int j = 0; j < 3; j++) { |
| 54 | + if (grid[i + startRow][j + startCol] == num) |
| 55 | + return false; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + public static void main(String[] args) { |
| 63 | + int grid[][] = { { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, { 0, 8, 7, 0, 0, 0, 0, 8, 0 }, |
| 64 | + { 0, 0, 3, 0, 1, 3, 0, 0, 5 }, { 9, 0, 0, 8, 6, 0, 6, 0, 0 }, { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, |
| 65 | + { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, { 0, 0, 5, 2, 0, 6, 3, 0, 0 }, }; |
| 66 | + |
| 67 | + if (solveSudoku(grid, 0, 0)) |
| 68 | + print(grid); |
| 69 | + else |
| 70 | + System.out.println("No Solution exists"); |
| 71 | + } |
| 72 | +} |
0 commit comments