解答数独

RT:

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.

代码如下:不过有一个前提,有3×3的小方格内也必须满足不能出现相同数字的约定,所以回溯的时候加上了一个g.

    bool s(vector<vector<char> > &n,vector<map<char, int> > & rows, vector<map<char, int> > & clo, int i, int j,vector<map<int, int> >& g)
    {
        for (; i < 9; ++i)
        {
            bool finded = false;
            for (; j < 9; ++j)
            {
                if (n[i][j] == '.')
                {
                    finded = true;
                    break;
                }
            }
            if (finded)
                break;
            j = 0;
        }
        if (i == 9)
            return true;
        vector<char> selects;
        for (char k = '1'; k <= '9'; ++k)
        {
            if (rows[i][k] == 0 && clo[j][k] == 0&& g[((i/3)*3+(j/3))][k] == 0)
            {
                selects.push_back(k);
            }
        }
        if (selects.size() == 0)
            return false;
        reverse(selects.begin(), selects.end());
        for (int h = 0; h < selects.size(); ++h)
        {
            rows[i][selects[h]] = 1;
            clo[j][selects[h]] = 1;
            g[((i/3)*3+(j/3))][selects[h]] = 1;
            n[i][j] = selects[h];
            if (s(n, rows, clo, i + ((j+1)/9), (j + 1)%9,g))
                return true;
            n[i][j] = '.';
            g[((i/3)*3+(j/3))][selects[h]] = 0;
            rows[i][selects[h]] = 0;
            clo[j][selects[h]] = 0;
        }
        return false;
    }
    
    void solveSudoku(vector<vector<char> > &board) 
    {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<map<char, int> > rows, clos;
        rows.resize(9);
        clos.resize(9);
        vector<map<int, int> > g;
        g.resize(9);
        for (int i = 0; i < 9; ++i)
            for (char j = '1'; j <= '9' ; ++j)
            {
                g[i][j] = 0;
                rows[i][j] = 0;
                clos[i][j] = 0;
            }
            
        for (int i = 0; i < 9; ++i)
            for (int j = 0; j < 9; ++j)
            {
                if (board[i][j] != '.')
                {
                    g[((i/3)*3+(j/3))][board[i][j]] = 1;
                    rows[i][board[i][j]] = 1;
                    clos[j][board[i][j]] = 1;
                }
            }
        s(board, rows, clos, 0, 0,g);
    }

  

posted @ 2012-12-29 21:56  David Luo  阅读(202)  评论(0编辑  收藏  举报