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

    本题是求解数独,采用回溯的算法,依次寻找。时间:92ms。代码如下:

    class Solution {
    public:
        bool isValid(vector<vector<char>>& board, size_t i, size_t j){
            for (size_t x = 0; x < 9; ++x){
                if (board[x][j] == board[i][j] && x != i)
                    return false;
            }
            for (size_t y = 0; y < 9; ++y){
                if (board[i][y] == board[i][j] && y != j)
                    return false;
            }
            for (size_t x = 3 * (i / 3); x < 3 * (i / 3) + 3; ++x){
                for (size_t y = 3 * (j / 3); y < 3 * (j / 3) + 3; ++y){
                    if (board[x][y] == board[i][j] && x != i && y != j)
                        return false;
                }
            }
            return true;
        }
        bool makeSolveSudoku(vector<vector<char>>& board) {
            for (size_t i = 0; i < 9; ++i){
                for (size_t j = 0; j < 9; ++j){
                    if (board[i][j] == '.'){
                        for (int k = 1; k <= 9; ++k){
                            board[i][j] = k + '0';
                            if (isValid(board, i, j) && makeSolveSudoku(board))
                                return true;
                            board[i][j] = '.';
                        }
                        return false;
                    }
                }
            }
            return true;
        }
        void solveSudoku(vector<vector<char>>& board) {
            makeSolveSudoku(board);
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    牌库读取的修复
    法术迸发(Spellburst)
    传染孢子的探索
    降低电脑功耗——降低笔记本风扇噪音
    Playfield 类方法的注释
    大陆争霸( 最短路变形)
    POJ 2406 Power String
    括号匹配
    HDU 1003 最大子段和
    6.19noip模拟赛总结
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4580091.html
Copyright © 2011-2022 走看看