标签:
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.‘
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
1 public class Solution { 2 3 public void solveSudoku(char[][] board) { 4 doSolveSudoku(board); 5 } 6 private boolean doSolveSudoku(char[][] board) { 7 for (int i = 0; i < 9; i++) { 8 for (int j = 0; j < 9; j++) { 9 if (‘.‘ == board[i][j]) { 10 for (int k = 1; k <= 9; k++) { 11 board[i][j] = (char) (‘0‘ + k); 12 if (isValid(board, i, j)) { 13 if (doSolveSudoku(board)) { 14 return true; 15 } 16 } 17 board[i][j]=‘.‘; 18 } 19 return false; 20 } 21 } 22 } 23 return true; 24 } 25 private boolean isValid(char[][] board, int x, int y) { 26 int row,col; 27 for (row = 0; row < 9; row++) { 28 if ((x != row) && (board[row][y] == board[x][y])) { 29 return false; 30 } 31 } 32 for (col = 0; col < 9; col++) { 33 if ((y != col) && (board[x][y] == board[x][col])) { 34 return false; 35 } 36 } 37 for (row = (x/3)*3; row <(x/3+1)*3 ; row++) { 38 for (col = (y/3)*3; col <(y/3+1)*3 ; col++) { 39 if ((x != row) && (y != col) && (board[x][y] == board[row][col])) { 40 return false; 41 } 42 } 43 } 44 return true; 45 } 46 }
标签:
原文地址:http://www.cnblogs.com/birdhack/p/4268852.html