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     }
  • 相关阅读:
    02作业
    作业01
    10-C++远征之模板篇-学习笔记
    9-C++远征之多态篇-学习笔记
    8-C++远征之继承篇-学习笔记
    C++远征之封装篇(下)-学习笔记
    6-C++远征之封装篇[上]-学习笔记
    C++远征离港篇-学习笔记
    4-c++教程起航篇-学习笔记
    Linux C语言结构体-学习笔记
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3442867.html
Copyright © 2011-2022 走看看