• 37. Sudoku 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.

    如果当前位置是空,则尝试1到9中所有的数字,如果对于1到9中的某些数字,当前是合法的,则继续尝试下一个位置(调用自身)。

     1 public class Solution {
     2     public void solveSudoku(char[][] board) {
     3         if(board == null || board.length == 0)
     4             return;
     5         solve(board);
     6     }
     7     
     8     public boolean solve(char[][] board){
     9         for(int i = 0; i < board.length; i++){
    10             for(int j = 0; j < board[0].length; j++){
    11                 if(board[i][j] == '.'){
    12                     for(char c = '1'; c <= '9'; c++){//trial. Try 1 through 9
    13                         if(isValid(board, i, j, c)){
    14                             board[i][j] = c; //Put c for this cell
    15                             
    16                             if(solve(board))
    17                                 return true; //If it's the solution return true
    18                             else
    19                                 board[i][j] = '.'; //Otherwise go back
    20                         }
    21                     }
    22                     
    23                     return false;
    24                 }
    25             }
    26         }
    27         return true;
    28     }
    29     
    30     private boolean isValid(char[][] board, int row, int col, char c){
    31         for(int i = 0; i < 9; i++) {
    32             if(board[i][col] != '.' && board[i][col] == c) return false; //check row
    33             if(board[row][i] != '.' && board[row][i] == c) return false; //check column
    34         }
    35         for(int i = 3*(row/3);i<3*(row/3+1);i++)
    36             for(int j = 3*(col/3);j<3*(col/3+1);j++)
    37             if(board[i][j] != '.' && board[i][j] == c) return false; //check 3*3 block
    38         
    39         return true;
    40     }
    41 }
  • 相关阅读:
    毕业一年的广州之行
    js一个抽奖的例子
    关于position:absolute的困惑
    px,pt,em,rem
    HTML4.01和XHTML1.0和XHTML1.1的一些区别
    通过微信分享链接,后面会被加上from=singlemessage&isappinstalled=1可能导致网页打不开
    windows无提示关闭页面
    canvas画随机闪烁的星星
    angular背景图片问题
    Python爬虫(二)— Python3内置模块 Urllib
  • 原文地址:https://www.cnblogs.com/zle1992/p/8916408.html
Copyright © 2020-2023  润新知