• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
36. Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

检查有数字的格子是否组成合法的数独。

 

用row_mask[i][j]来记录第i行是否出现过数字j。

bool isValidSudoku(vector<vector<char> > &board) {
    const int cnt = 9;
    bool row_mask[cnt][cnt] = {false};
    bool col_mask[cnt][cnt] = {false};
    bool area_mask[cnt][cnt] = {false};
    //check each rows and cols
    for(int r=0; r<board.size(); r++){
        for (int c=0; c<board[r].size(); c++){
            if (!isdigit(board[r][c])) continue;
            int idx =  board[r][c] - '0' - 1;
                
            //check the rows
            if (row_mask[r][idx] == true){
                return false;
            }
            row_mask[r][idx] = true;
                
            //check the cols
            if (col_mask[c][idx] == true) {
                return false;
            }
            col_mask[c][idx] = true;
                
            //check the areas
            int area = (r/3) * 3 + (c/3);
            if (area_mask[area][idx] == true) {
                return false;
            }
            area_mask[area][idx] = true;
        }
    }
        
    return true;
}

 

posted on 2016-03-05 16:17  ArgenBarbie  阅读(162)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3