[leetcode] 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.
https://oj.leetcode.com/problems/sudoku-solver/
思路:类似于N-Queens的回溯方案,对于每个空格,依次填入每个数字,如果合法,继续下去,直至填满。
注意:此时isValid只需比较当前填入的值所在区域的合法性!
/** * http://blog.csdn.net/zxzxy1988/article/details/8586289 * http://blog.csdn.net/linhuanmars/article/details/20748761 * @author Dong Jiang * */ public class Solution { public void solveSudoku(char[][] board) { solve(board); } public boolean solve(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '.') { for (int k = 1; k <= 9; k++) { board[i][j] = (char) ('0' + k); if (isValid(board, i, j) && solve(board)) return true; board[i][j] = '.'; } return false; } } } return true; } private boolean isValid(char[][] board, int x, int y) { int i, j; for (i = 0; i < 9; i++) if (i != x && board[i][y] == board[x][y]) return false; for (j = 0; j < 9; j++) if (j != y && board[x][j] == board[x][y]) return false; for (i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++) for (j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++) if (i != x && j != y && board[i][j] == board[x][y]) return false; return true; } public static void main(String[] args) { char[][] board = { { '5', '3', '.', '.', '7', '.', '.', '.', '.' }, { '6', '.', '.', '1', '9', '5', '.', '.', '.' }, { '.', '9', '8', '.', '.', '.', '.', '6', '.' }, { '8', '.', '.', '.', '6', '.', '.', '.', '3' }, { '4', '.', '.', '8', '.', '3', '.', '.', '1' }, { '7', '.', '.', '.', '2', '.', '.', '.', '6' }, { '.', '6', '.', '.', '.', '.', '2', '8', '.' }, { '.', '.', '.', '4', '1', '9', '.', '.', '5' }, { '.', '.', '.', '.', '8', '.', '.', '7', '9' } }; new Solution().solveSudoku(board); } }
第二遍记录:依次填入数字,传入坐标的方法依然有问题,有待调试。
参考
http://blog.csdn.net/linhuanmars/article/details/20748761
http://blog.csdn.net/zxzxy1988/article/details/8586289