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.

    Solution: back-tracking..

     1 class Solution {
     2 public:
     3     typedef vector<vector<char> > BOARDTYPE;
     4     
     5     void solveSudoku(BOARDTYPE &board) {
     6         solveSudokuRe(board, 0, 0);
     7     }
     8     
     9     bool solveSudokuRe(BOARDTYPE &board, int row, int col) {
    10         getNextEmpty(board, row, col); // get next empty position [row, col]
    11         if(row == 9) return true;
    12         vector<bool> avail(9, true);
    13         getAvailable(board, avail, row, col); // available value in row/row/box
    14         for(int i = 0; i < 9; ++i) {
    15             if (!avail[i]) continue;
    16             board[row][col] = i + '1';
    17             if (solveSudokuRe(board, row, col)) return true;
    18         }
    19         board[row][col] = '.';
    20         return false;
    21     }
    22     
    23     void getNextEmpty(BOARDTYPE &board, int &row, int &col) {
    24         do {
    25             if (board[row][col] == '.') return;
    26             row = (col == 8) ? row + 1 : row;
    27             col = (col + 1) % 9;
    28         } while (row < 9);
    29     }
    30     
    31     void getAvailable(BOARDTYPE &board, vector<bool> &avail, int row, int col) {
    32         for (int i = 0; i < 9; ++i) {
    33             if (board[row][i] != '.') avail[board[row][i]-'1'] = false;
    34             if (board[i][col] != '.') avail[board[i][col]-'1'] = false;
    35             int box_i = row/3*3 + i/3, box_j = col/3*3 + i%3;
    36             if (board[box_i][box_j] != '.') avail[board[box_i][box_j]-'1'] = false;
    37         }
    38     }
    39 };
  • 相关阅读:
    lanya
    Apple watch ,小米微信通知
    jenkins grunt 自动构建流程
    刷机步骤
    ipad忘记了锁屏密码,已经越狱了
    ar
    如何在ubuntu中安装php
    阿里云
    docker swarm 集群及可视化界面的安装及配置
    https://github.com/gaoyangxiaozhu/DockerVI
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682063.html
Copyright © 2011-2022 走看看