zoukankan      html  css  js  c++  java
  • [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.

    Solution:

    http://blog.csdn.net/zxzxy1988/article/details/8586289

     1 public class Solution {
     2     public void solveSudoku(char[][] board) {
     3         mySudokuSolver(board);
     4     }
     5 
     6     private boolean mySudokuSolver(char[][] board) {
     7         // TODO Auto-generated method stub
     8         for(int i=0;i<board.length;++i){
     9             for(int j=0;j<board[0].length;++j){
    10                 if(board[i][j]=='.'){
    11                     for(int k=1;k<=9;++k){
    12                         board[i][j]=(char) (k+'0');
    13                         if(isValid(board,i,j)&&mySudokuSolver(board)){
    14                             return true;
    15                         }
    16                         board[i][j]='.';  //这里这个细节不要忘掉!!,你把后边儿的“.“改成数字后,发现做不下去了,得回溯,那你
                               //得把这个数字改回"."啊
    17 } 18 return false; 19 } 20 } 21 } 22 return true; 23 } 24 25 private boolean isValid(char[][] board, int row, int col) { 26 // TODO Auto-generated method stub 27 for(int i=0;i<board.length;++i){ 28 if(i!=row&&board[i][col]==board[row][col]) 29 return false; 30 } 31 for(int i=0;i<board[0].length;++i){ 32 if(i!=col&&board[row][i]==board[row][col]) 33 return false; 34 } 35 for(int i=(row/3)*3;i<(row/3+1)*3;++i){ 36 for(int j=(col/3)*3;j<(col/3+1)*3;++j){ 37 if(i!=row&&j!=col&&board[i][j]==board[row][col]) 38 return false; 39 } 40 } 41 return true; 42 } 43 }
  • 相关阅读:
    php中file_get_contents的图片乱码
    Lsh and Rsh (左移和右移)
    |=的含义
    Intercultural Communication Drama
    VS代码块快速折叠快捷键
    C++sqrt()函数与sqrtf()函数的区别
    C++中union和struct之间的区别
    泛型编程
    生成百度网盘目录文件
    字符串前L的含义
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4137277.html
Copyright © 2011-2022 走看看