標籤:style blog http color os io for ar
Sudoku Solver
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.
演算法思路:
典型的DFS,與N-Queens其實沒太大區別,只是衝突不同,而衝突的判斷方式,在[leetcode]Valid Sudoku中已經講得很清楚了。
代碼如下:
1 public class Solution { 2 boolean over = false; 3 public void solveSudoku(char[][] board) { 4 if(board == null || board.length != 9 || board[0].length != 9) return; 5 boolean[][] row = new boolean[9][9]; 6 boolean[][] col = new boolean[9][9]; 7 boolean[][] matrix = new boolean[9][9]; 8 for(int i = 0; i < 9; i++){//初始化衝突表 9 for(int j = 0; j < 9; j++){10 if(board[i][j] != ‘.‘){11 int n = board[i][j] - ‘1‘;12 row[i][n] = col[j][n] = matrix[i - i % 3 + j / 3][n] = true;13 }14 }15 }16 dfs(board,0,0,row,col,matrix);17 }18 private void dfs(char[][] board,int i ,int j,boolean[][] row,boolean[][] col,boolean[][] matrix){19 if(i > 8){20 over = true;21 return;22 }23 if(board[i][j] != ‘.‘){24 if(j < 8){25 dfs(board, i, j + 1, row, col, matrix);26 }else{27 dfs(board, i + 1, 0, row, col, matrix);28 }29 }else{30 for(int k = 0; k < 9; k++){31 if(row[i][k] || col[j][k] || matrix[i - i % 3 + j / 3][k]) continue;32 row[i][k] = col[j][k] = matrix[i - i % 3 + j / 3][k] = true;33 board[i][j] = (char)(‘1‘ + k);34 if(j < 8){35 dfs(board, i, j + 1, row, col, matrix);36 }else{37 dfs(board, i + 1, 0, row, col, matrix);38 }39 if(over) return;40 row[i][k] = col[j][k] = matrix[i - i % 3 + j / 3][k] = false;41 board[i][j] = ‘.‘;42 }43 }44 }45 }