leetcode - Sudoku Solver

本文介绍了一个使用C++实现的数独求解程序,通过填充空单元格来解决数独谜题。文章详细展示了如何利用位操作高效地检查行、列和宫格中的数字,并递归地尝试所有可能的解决方案,直到找到唯一正确答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

//'__builtin_ffs' is gcc compiler intrinsic to find the first '1' bit of the input integer
class Solution
{
public:
    void solveSudoku( std::vector<std::vector<char> > &board )
    {
        struct { short o; short v; } b[81] = { 0 };

        short r[9], c[9], s[9];
        for( int i = 0; i < 9; ++i )
            r[i] = c[i] = s[i] = 0x01ff;
            
        for( int i = 0; i < 81; ++i )
        {
            int x = i % 9, y = i / 9;
            int z = x / 3 * 3 + y / 3;
            short a = board[y][x];
            if( a != '.' )
            {
                b[i].o = -1;
                a = ~(1 << (a - '1'));
                r[y] &= a, c[x] &= a, s[z] &= a;
            }
        }
        
        
        for( int i = 0; i < 81; ++i )
        {
            if( b[i].o != -1 )
            {
                int x = i % 9, y = i / 9;
                int z = x / 3 * 3 + y / 3;
                b[i].o = b[i].v = r[y] & c[x] & s[z];
            }
        }


        for( int i = 0; i < 81; ++i )
        {
            if( b[i].o == -1 )
                continue;

            int x = i % 9, y = i / 9;
            int z = x / 3 * 3 + y / 3;
            int v = b[i].v & r[y] & c[x] & s[z];
            if( v == 0 ) 
            {
                for( --i; i >= 0; --i )
                {
                    if( b[i].o == -1 )
                        continue;
                    x = i % 9, y = i / 9;
                    z = x / 3 * 3 + y / 3;
                    short a = (short)(1 << (__builtin_ffs( b[i].v ) - 1));
                    r[y] |= a, c[x] |= a, s[z] |= a;
                    if( (v = b[i].v & ~a) != 0 )
                        break;
                    b[i].v = b[i].o;
                }
            }

            b[i].v = v;
            short a = ~(short)(1 << (__builtin_ffs( b[i].v ) - 1));
            r[y] &= a, c[x] &= a, s[z] &= a;
        }


        for( int i = 0; i < 81; ++i )
        {
            if( b[i].o != -1 )
            {
                int x = i % 9, y = i / 9;
                board[y][x] = __builtin_ffs( b[i].v ) - 1 + '1';
            }
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值