zoukankan      html  css  js  c++  java
  • 数独问题

    问题: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.

    回答:

    bool isValid(vector<vector<char> > &board, int px, int py) {
        int len = board.size();
        
        //check rows and cols.
        for (int i = 0; i < len; ++i)
        {
            if(i != py && board[px][i] == board[px][py] ||
                i != px && board[i][py] == board[px][py])
                return false;
        }

        //check box
        int basex = px/3 * 3;
        int basey = py/3 * 3;
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
            {
                if( basex + i != px &&
                    basey + j != py &&
                    board[basex + i][basey + j] == board[px][py])
                    return false;
            }
        return true;
    }

    bool currentSudoku(vector<vector<char> > &board) {

        for (int row = 0; row < 9; ++row)
            for (int col = 0; col < 9; ++col)
            {
                if(board[row][col] == '.')
                {
                    for(char num = '1'; num <= '9'; ++num)
                    {
                        board[row][col] = num;
                        if(isValid(board, row, col) && currentSudoku(board))
                        return true;
                        board[row][col] = '.';
                    }
                    return false;//no number can add in this point.
                }
            }
        return true;
    }

    void solveSudoku(vector<vector<char> > &board) {
        currentSudoku(board);
    }

  • 相关阅读:
    【EFCORE笔记】自动生成属性的显式值
    【EFCORE笔记】更新数据的多种方案
    【EFCORE笔记】添加数据的多种方案
    【EFCORE笔记】多租户系统的最佳实践
    【EFCORE笔记】全局查询筛选器
    【EFCORE笔记】异步查询&工作原理&注释标记
    【EFCORE笔记】执行原始SQL查询
    003_Redis后台启动(windows10与)
    Office 2010后 如何保存新的样式集
    Mysql启动 发生系统错误 1067
  • 原文地址:https://www.cnblogs.com/benchao/p/4525337.html
Copyright © 2011-2022 走看看