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

    思路:

    搜索,类似八皇后
    代码:

     1     bool search(vector<vector<char> > &board, vector<vector<bool> > &rows, vector<vector<bool> > &cols, vector<vector<bool> > &blocks, int x, int y){
     2         if(x == 9 && y == 0)
     3             return true;
     4         int nx, ny;
     5         ny = y+1;
     6         nx = x;
     7         if(ny == 9){
     8             ny = 0;
     9             nx++;
    10         }
    11         if(board[x][y] != '.'){
    12             return search(board, rows, cols, blocks, nx, ny);
    13         }
    14         else{
    15             for(int i = 0; i < 9; i++){
    16                 if(!rows[x][i] && !cols[y][i] && !blocks[x/3*3+y/3][i]){
    17                     rows[x][i] = true;
    18                     cols[y][i] = true;
    19                     blocks[x/3*3+y/3][i] = true;
    20                     board[x][y] = i+1+'0';
    21                     if(search(board, rows, cols, blocks, nx, ny))
    22                         return true;
    23                     board[x][y] = '.';
    24                     rows[x][i] = false;
    25                     cols[y][i] = false;
    26                     blocks[x/3*3+y/3][i] = false;
    27                 }
    28             }
    29             return false;
    30         }
    31     }
    32     void solveSudoku(vector<vector<char> > &board) {
    33         // IMPORTANT: Please reset any member data you declared, as
    34         // the same Solution instance will be reused for each test case.
    35         vector<vector<bool> > rows(9, vector<bool>(9, false));
    36         vector<vector<bool> > cols(9, vector<bool>(9, false));
    37         vector<vector<bool> > blocks(9, vector<bool>(9, false));
    38         for(int i = 0; i < 9; i++){
    39             for(int j = 0; j < 9; j++){
    40                 if(board[i][j] != '.'){
    41                     int num = board[i][j]-'0';
    42                     rows[i][num-1] = true;
    43                     cols[j][num-1] = true;
    44                     blocks[i/3*3+j/3][num-1] = true;
    45                 }
    46             }
    47         }
    48         search(board, rows, cols, blocks, 0, 0);
    49     }
  • 相关阅读:
    Hive 使用问题集锦
    scala def/val/lazy val区别以及call-by-name和call-by-value
    spark学习流程
    Hadoop
    Hive
    Chrome快捷键
    Java API帮助文档
    Java 访问修饰符与非访问修饰符
    java 关键字
    Solr配置Ikanalyzer分词器
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3442867.html
Copyright © 2011-2022 走看看