Last active
August 29, 2015 14:26
-
-
Save am5a03/93d681d7790805def022 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sudoku; | |
/** | |
* Created by Raymond on 2015-08-01. | |
*/ | |
public class Solver { | |
private static final int MAX_ROW = 9; | |
private static final int MAX_COL = 9; | |
public boolean solve(int[][] board, int row, int col) { | |
// Return condition, the board has reached the end | |
if (row == MAX_ROW) return true; | |
// Only modify non-filled cell | |
if (board[row][col] != 0) { | |
if (col == 8) { | |
if (solve(board, row + 1, 0)) return true; | |
} else { | |
if (solve(board, row, col + 1)) return true; | |
} | |
} | |
//Try number 1-9 | |
for (int num = 1; num <= 9; num++) { | |
if (isValid(num, board, row, col)) { | |
board[row][col] = num; | |
if (col == 8) { | |
if (solve(board, row + 1, 0)) return true; | |
} else { | |
if (solve(board, row, col + 1)) return true; | |
} | |
} | |
} | |
board[row][col] = 0; //Backtrack here, reset the cell to 0 | |
return false; | |
} | |
/** | |
* | |
* @param num | |
* @param board | |
* @param row | |
* @param col | |
* @return | |
*/ | |
protected boolean isValid(int num, int[][] board, int row, int col) { | |
return isRowValid(num, board, row) && isColValid(num, board, col) && isBoxValid(num, board, row, col); | |
} | |
/** | |
* | |
* @param num | |
* @param board | |
* @param row | |
* @return | |
*/ | |
private boolean isRowValid(int num, int[][] board, int row) { | |
for (int col = 0; col < MAX_COL; col++) { | |
if (num == board[row][col]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
/** | |
* | |
* @param num | |
* @param board | |
* @param col | |
* @return | |
*/ | |
private boolean isColValid(int num, int[][] board, int col) { | |
for (int row = 0; row < MAX_ROW; row++) { | |
if (num == board[row][col]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
/** | |
* | |
* @param num | |
* @param board | |
* @param row | |
* @param col | |
* @return | |
*/ | |
private boolean isBoxValid(int num, int[][] board, int row, int col) { | |
int startingRow = row/3; | |
int startingCol = col/3; | |
for (int i = startingRow * 3; i < startingRow + 3; i++) { | |
for (int j = startingCol * 3; j < startingCol + 3; j++) { | |
if (num == board[i][j]) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment