标签:
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.
public class Solution { public void solveSudoku(char[][] board) { sudokuHelper(board); } public boolean sudokuHelper(char[][] board) { for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { if(board[i][j]!=‘.‘)continue; for(int k=1;k<=9;k++) { board[i][j]=(char) (k+‘0‘); if(isValid(board,i,j) && sudokuHelper(board)) { return true; } board[i][j]=‘.‘; } return false; } } return true; } public boolean isValid(char[][] board, int a, int b) { Set<Character> set = new HashSet<Character>(); //row for(int i=0;i<9;i++) { if(set.contains(board[a][i])) return false; if(board[a][i]>‘0‘&&board[a][i]<=‘9‘) { set.add(board[a][i]); } } //col set = new HashSet<Character>(); for(int i=0;i<9;i++) { if(set.contains(board[i][b])) return false; if(board[i][b]>‘0‘&&board[i][b]<=‘9‘) { set.add(board[i][b]); } } //box set = new HashSet<Character>(); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { int x = a/3*3+i; int y = b%3*3+j; if(set.contains(board[x][y])) return false; if(board[x][y]>‘0‘&&board[x][y]<=‘9‘) { set.add(board[x][y]); } } } return true; } }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/5648382.html