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

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.

const int SodukuSize = 9;
bool row_mask[SodukuSize][SodukuSize];
bool col_mask[SodukuSize][SodukuSize];
bool area_mask[SodukuSize][SodukuSize];

bool initSudokuMask(vector< vector<char> > &board){
    //reset the memory
    memset(row_mask, false, sizeof(row_mask));
    memset(col_mask, false, sizeof(col_mask));
    memset(area_mask, false, sizeof(area_mask));

    //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/cols/areas
            int area = (r/3) * 3 + (c/3);
            if (row_mask[r][idx] || col_mask[c][idx] || area_mask[area][idx] ){
                return false;
            }
            row_mask[r][idx] = col_mask[c][idx] = area_mask[area][idx] = true;
        }
    }
    return true;
}


bool recursiveSudoKu(vector< vector<char> > &board, int row, int col){

    if (row >= SodukuSize) {
        return true;
    }

    if (col >= SodukuSize){
        return recursiveSudoKu(board, row+1, 0);
    }
    
    if (board[row][col] != '.'){
        return recursiveSudoKu(board, row, col+1);    
    }
    //pick a number for empty cell
    int area;
    for(int i=0; i<SodukuSize; i++){
        area = (row/3) * 3 + (col/3);
        if (row_mask[row][i] || col_mask[col][i] || area_mask[area][i] ){
            continue;
        }
        //set the number and sovle it recursively
        board[row][col] = i + '1';
        row_mask[row][i] = col_mask[col][i] = area_mask[area][i] = true;
        if (recursiveSudoKu(board, row, col+1) == true){
            return true;
        }
        //backtrace
        board[row][col] = '.';
        row_mask[row][i] = col_mask[col][i] = area_mask[area][i] = false;
    }
    return false;
}

 

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