LeetCode-37.Sudok Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.


A sudoku puzzle...


...and its solution numbers marked in red.

Note:

    • The given board contain only digits 1-9 and the character '.'.
    • You may assume that the given Sudoku puzzle will have a single unique solution.
    • The given board size is always 9x9.

 

判断当前插入的值有没有错误,没有继续填下面的

 1 class Solution {//剪枝 mytip
 2     public void solveSudoku(char[][] board) {
 3         if(null==board ||0==board.length)
 4             return;
 5         help(board);
 6     }
 7     private boolean help(char[][] board){
 8         for (int row = 0; row < board.length; row++) {
 9             for (int col = 0; col < board.length; col++) {
10                 if('.'==board[row][col]){
11                     for (char i = '1'; i <= '9'; i++) {
12                         if(isValidSudoku(board,row,col,i)){
13                             board[row][col]=i;
14                             if(help(board)){
15                                 return true;
16                             }
17                             else{
18                                 board[row][col]='.';
19                             }
20                         }
21                     }
22                     return false;
23                 }
24             }
25         }
26         return true;
27     }
28     private boolean isValidSudoku(char[][] board,int row,int col,char ch) {
29         for (int i = 0; i <board.length ; i++) {
30             if(ch==board[row][i]||ch==board[i][col]){
31                 return false;
32             }
33         }
34         int r = row/3*3;
35         int c = col/3*3;
36         for (int i = r; i <r+3 ; i++) {
37             for (int j = c; j < c+3 ; j++) {
38                 if(ch==board[i][j]){
39                     return false;
40                 }
41             }
42         }
43 
44         return true;
45     }
46 }

 另外可以通过以下方式加速

相关题

有效的数独 LeetCode36 https://www.cnblogs.com/zhacai/p/10622779.html

posted @ 2019-03-29 17:39  月半榨菜  阅读(159)  评论(0编辑  收藏  举报