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

LeetCode "Sudoku Solver"

时间:2014-08-16 07:29:10      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   amp   

Simply DFS + Backtrace, as N-Queen

class Solution {
public:
    vector<unordered_set<char>> rows;
    vector<unordered_set<char>> cols;
    vector<vector<unordered_set<char>>> subboxHm;

    bool isValid(char c, int i, int j)
    {
        return (rows[j].find(c) == rows[j].end() &&
                cols[i].find(c) == cols[i].end() &&
                subboxHm[j/3][i/3].find(c) == subboxHm[j/3][i/3].end());
    }
    void putRecord(char c, int i, int j, vector<vector<char> > &board)
    {
        board[j][i] = c;
        rows[j].insert(c);
        cols[i].insert(c);
        subboxHm[j/3][i/3].insert(c);
    }
    void clearRecord(char c, int i, int j, vector<vector<char> > &board)
    {
        board[j][i] = .;
        rows[j].erase(c);
        cols[i].erase(c);
        subboxHm[j/3][i/3].erase(c);
    }
    bool goDFS(vector<vector<char> > &board)
    {
        size_t cnt = board.size();
        for(int j = 0; j < cnt; j ++)
        for(int i = 0; i < cnt; i ++)
        {
            char c = board[j][i];
            if (c == .)
            {
                for(char c = 1; c <= 9; c ++)
                {
                    if(isValid(c, i, j))
                    {                        
                        putRecord(c, i, j, board);
                        if(goDFS(board))    return true;
                        else                clearRecord(c, i, j, board);
                    }
                }
                return false;
            }
        }
        return true;
    }
    void solveSudoku(vector<vector<char> > &board) {
        size_t cnt = board.size();
        //    Init
        rows.resize(cnt);
        cols.resize(cnt);
        subboxHm.resize(cnt/3);
        for(int i = 0; i < cnt/3; i ++)
            subboxHm[i].resize(cnt/3);
        
        //    Fill in original record
        for(int j = 0; j < cnt; j ++)
        for(int i = 0; i < cnt; i ++)
        {
            char c = board[j][i];
            if (c != .)
            {
                rows[j].insert(c);
                cols[i].insert(c);
                unordered_set<char> &sb = subboxHm[j/3][i/3];
                sb.insert(c);
            }
        }

        goDFS(board);
    }
};

LeetCode "Sudoku Solver",布布扣,bubuko.com

LeetCode "Sudoku Solver"

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/tonix/p/3915954.html

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