Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Here another memory for speed implementation:

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        size_t row_cnt = board.size();
        size_t col_cnt = board[0].size();
        
        vector<vector<unordered_set<char>>> subbox_rec; subbox_rec.resize(row_cnt/3);
        for (int i = 0; i < row_cnt/3; i++)
            subbox_rec[i].resize(col_cnt/3);
        vector<unordered_set<char>> row_rec; row_rec.resize(row_cnt);
        vector<unordered_set<char>> col_rec; col_rec.resize(col_cnt);

        for (int j = 0; j < row_cnt; j ++)
        for (int i = 0; i < col_cnt; i++)
        {
            char c = board[j][i];
            if (c != '.')
            {
                //    Row
                if (row_rec[j].find(c) == row_rec[j].end())
                    row_rec[j].insert(c);
                else return false;
                //    Col
                if (col_rec[i].find(c) == col_rec[i].end())
                    col_rec[i].insert(c);
                else return false;
                //    subbox
                unordered_set<char> &sb = subbox_rec[j / 3][i / 3];
                if (sb.find(c) == sb.end())
                    sb.insert(c);
                else return false;

            }
        }
        return true;
    }
};
posted on 2014-08-15 12:20  Tonix  阅读(147)  评论(0编辑  收藏  举报