• 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 }
  • 相关阅读:
    2017年5月24日 HTML 基础知识(二)
    2017年5月22日 HTML基础知识(一)
    尼采语录
    Unicode字符串和整数和浮点数
    转义字符
    python第一节
    C# ASP .NET WEB方向和WPF方向,我该如何去选择
    ORA-06550:line 1,column 7;PLS-00201:indentifer '存储过程' must be declared;...PL/SQL Statement ignored 问题
    C# WPF打印报表
    Sql Server 自定义数据类型
  • 原文地址:https://www.cnblogs.com/zle1992/p/8916408.html
Copyright © 2020-2023  润新知