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.

    image

    A sudoku puzzle...

    image

    ...and its solution numbers marked in red.

    大意就是给你一个不完成的数独, 让你填完整。

    直接dfs, 用三个数组记录行,列, 块就可以了

    class Solution {
        bool dfs(vector<vector<char>>& board, bool row[10][10], bool val[10][10], bool rtl[10][10], int x, int y)
        {
            while(x < 9 && y < 9 && board[x][y] != '.')
            {
                y ++;
                if(y == 9)
                    x ++, y = 0;
            }
            
            if(x >= 9)
                return true;
            
            for(int i=1; i<10; ++ i)
            {
                if(row[x][i] == false &&  val[y][i] == false &&  rtl[x/3*3+y/3][i] == false)
                {
                    board[x][y] = '0' + i;
                    row[x][i] = val[y][i] = rtl[x/3*3+y/3][i] = true;
                    
                    if(dfs(board, row, val, rtl, x + (y+1 == 9), (y+1==9) ? 0 : y + 1))
                        return true;
                    
                    row[x][i] = val[y][i] = rtl[x/3*3+y/3][i] = false;
                }
            }
            board[x][y] = '.';
            return false;
        }
    public:
        void solveSudoku(vector<vector<char>>& board) {
            
            bool row[10][10], val[10][10], rtl[10][10];
            memset(row, false, sizeof(row));
            memset(val, false, sizeof(val));
            memset(rtl, false, sizeof(rtl));
            
            for(int i = 0; i < 9; ++ i)
            {
                for(int j = 0; j < 9; ++ j)
                {
                    if(board[i][j] == '.')
                        continue;
                    int t = board[i][j] - '0';
                    if(row[i][t] || val[j][t] || rtl[i / 3 * 3 + j / 3][t])
                        continue;
                    row[i][t] = val[j][t] = rtl[i / 3 * 3 + j / 3][t] = true;
                }
            }
            
            dfs(board, row, val, rtl, 0, 0);
        }
    };
    
  • 相关阅读:
    前端模块的前生今世
    variable fonts
    node
    webpack tree shaking
    es6 proxy浅析
    如何实现优美的骨架屏
    阿里巴巴Java开发手册建议创建HashMap时设置初始化容量,但是多少合适呢?
    新来个技术总监,禁止我们使用Lombok!
    2020年Java程序员应该学习的10大技术
    为啥HashMap的默认容量是16?
  • 原文地址:https://www.cnblogs.com/aiterator/p/6598047.html
Copyright © 2011-2022 走看看