题目
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 SudokuSolver { int N; int subSize; char[][] board; public void solveSudoku(char[][] board) { this.board = board; N = board.length; subSize = (int) Math.sqrt(N); solve(0); } private boolean solve(int index) { if (index == N * N) { return true; } int x = index / N; int y = index % N; if (board[x][y] == ‘.‘) { for (char c = ‘1‘; c <= ‘9‘; ++c) { if (isValidCell(x, y, c)) { board[x][y] = c; if (solve(index + 1)) { return true; } board[x][y] = ‘.‘; } } } else { return solve(index + 1); } return false; } private boolean isValidCell(int x, int y, char c) { // row for (int column = 0; column < N; ++column) { if (board[x][column] == c) { return false; } } // column for (int row = 0; row < N; ++row) { if (board[row][y] == c) { return false; } } // subboard int originRow = (x / subSize) * subSize; int originColumn = (y / subSize) * subSize; for (int i = 0; i < N; ++i) { int row = originRow + i / subSize; int column = originColumn + i % subSize; if (board[row][column] == c) { return false; } } return true; } }
LeetCode | Sudoku Solver,布布扣,bubuko.com
原文:http://blog.csdn.net/perfect8886/article/details/22979703