1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Valid Sudoku

Posted on 2014-01-09 15:09  1957  阅读(115)  评论(0编辑  收藏  举报

valid row

valid col

valid block

 

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board) {
        unordered_set<int> vis;
        //valid row
        for(int i = 0 ; i < 9 ; i++) { //enumerate row
            vis.clear();
            for(int j = 0 ; j < 9 ; j++) {
                if(board[i][j] == '.')
                  continue;
                else {
                  if(board[i][j] >= '1' && board[i][j] <= '9' && vis.find(board[i][j]) == vis.end()) {
                      vis.insert(board[i][j]);
                  } else {
                      return false;
                  }
                }
            }
        }
        //valid col
        for(int i = 0 ; i < 9 ; i++) {
            vis.clear();
            for(int j = 0 ; j < 9 ; j++) {
                //i col , j = row
                if(board[j][i] == '.')
                  continue;
                else {
                    if(board[j][i] >= '1' && board[j][i] <= '9' && vis.find(board[j][i]) == vis.end()){
                        vis.insert(board[j][i]);
                    } else {
                        return false;
                    }
                }
            }
        }
        //valid block
        for(int i = 0 ; i < 9 ; i += 3) {
            for(int j = 0 ; j < 9 ; j += 3) {
                //block start
                vis.clear();
                for(int row = 0 ; row < 3 ; row ++) {
                    for(int col = 0 ; col < 3 ; col ++) {
                        if(board[i + row][j + col] == '.')
                          continue;
                         else {
                             if (board[i + row][j + col] >= '1' && board[i + row][j + col] <= '9' && vis.find(board[i + row][j + col]) == vis.end()) {
                                 vis.insert(board[i + row][j + col]);
                             } else {
                                 return false;
                             }
                         }
                    }
                }
            }
        }
        return true;
    }
};