码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode - Sudoku Solver

时间:2014-10-25 17:27:41      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   for   sp   on   

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.

bubuko.com,布布扣

A sudoku puzzle...

bubuko.com,布布扣

...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';
            }
        }
    }
};


leetcode - Sudoku Solver

标签:style   http   color   io   os   ar   for   sp   on   

原文地址:http://blog.csdn.net/akibatakuya/article/details/40453283

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!