• #Leetcode# 37. Sudoku Solver


    https://leetcode.com/problems/sudoku-solver/

    Write a program to solve a Sudoku puzzle by filling the empty cells.

    A sudoku solution must satisfy all of the following rules:

    1. Each of the digits 1-9 must occur exactly once in each row.
    2. Each of the digits 1-9 must occur exactly once in each column.
    3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3sub-boxes of the grid.

    Empty cells are indicated by the character '.'.


    A sudoku puzzle...


    ...and its solution numbers marked in red.

    Note:

      • The given board contain only digits 1-9 and the character '.'.
      • You may assume that the given Sudoku puzzle will have a single unique solution.
      • The given board size is always 9x9.

    代码:

    class Solution {
    public:
        void solveSudoku(vector<vector<char> > &board) {
            if (board.empty() || board.size() != 9 || board[0].size() != 9) return;
            solveSudokuDFS(board, 0, 0);
        }
        bool solveSudokuDFS(vector<vector<char> > &board, int i, int j) {
            if (i == 9) return true;
            if (j >= 9) return solveSudokuDFS(board, i + 1, 0);
            if (board[i][j] == '.') {
                for (int k = 1; k <= 9; ++k) {
                    board[i][j] = (char)(k + '0');
                    if (isValid(board, i , j)) {
                        if (solveSudokuDFS(board, i, j + 1)) return true;
                    }
                    board[i][j] = '.';
                }
            } else {
                return solveSudokuDFS(board, i, j + 1);
            }
            return false;
        }
        bool isValid(vector<vector<char> > &board, int i, int j) {
            for (int col = 0; col < 9; ++col) {
                if (col != j && board[i][j] == board[i][col]) return false;
            }
            for (int row = 0; row < 9; ++row) {
                if (row != i && board[i][j] == board[row][j]) return false;
            }
            for (int row = i / 3 * 3; row < i / 3 * 3 + 3; ++row) {
                for (int col = j / 3 * 3; col < j / 3 * 3 + 3; ++col) {
                    if ((row != i || col != j) && board[i][j] == board[row][col]) return false;
                }
            }
            return true;
        }
    };
    

      数独 9*9 暴力就好了

  • 相关阅读:
    java基础1
    display:inline
    运用<ul><li>做导航栏
    ul和li 基本用法分析(这里主要想学习怎么用在导航栏中)
    转换(旋转)transform
    典型相关分析
    相关性模型-相关系数
    拟合算法
    插值算法
    评估类模型之优劣解距离法Topsis模型
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10685058.html
Copyright © 2020-2023  润新知