Sudoku Solver

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.


A sudoku puzzle...


...and its solution numbers marked in red.

1.我的解答:回溯

对每个位置进行遍历,并对这个位置用1~9去放置,看看符不符合。 用时比较多,不造为什么,可能还需优化

//
//  main.cpp
//  Sudo
//
//  Created by zjl on 16/4/30.
//  Copyright © 2016年 zjl. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
bool judge(vector<vector<char>> board, int r, int c, char target){
    for(int i = 0; i < 9; i++){
        if(board[r][i]==target || board[i][c]== target)
            return false;
    }
    int br = 3*(r/3), cr = 3*(c/3);
    for(int k = br; k < br+3; k++){
        for(int j = cr; j < cr+3; j++){
            if(board[k][j] == target)
                return false;
        }
    }
    return true;
}
void print_vec(vector<vector<char>> b){
    for(int p = 0; p < b.size();p++){
        for(int q = 0; q < b[p].size(); q++){
            cout<<b[p][q]<<" ";
        }
        cout<<endl;
    }
}
bool Sudo(vector<vector<char>>& board, int row, int col){
    bool b = false;
    if(board[row][col]!='.'){
        if(col+1 < 9){
            b =Sudo(board,row,col+1);
            if(b) return true;
        }
        else if(col+1 >= 9 && row+1 < 9){
            b = Sudo(board,row+1,0);
            if(b) return true;
        }else return true;//当遍历到最后一个了,结束了,就返回true
        return false;
    }else{
    for(int i = 1; i <= 9; i++){
        if(judge(board,row,col,i+'0')){
            board[row][col] = i+'0';
            if(col+1 < 9){
                b = Sudo(board,row,col+1);
                if(b) return true;
                else
                board[row][col] ='.';
            }
            else if(col+1 >= 9 && row+1 < 9){
                b = Sudo(board,row+1,0);
                if(b) return true;
                else board[row][col] ='.';
            }
            else
                return true;//当遍历到最后一个了,结束了,就返回true
        }
    }
      return false;
    }
   
}
void solveSudoku(vector<vector<char>>& board) {
    int i = 0, j = 0,label = 0;
    bool b = Sudo(board,i,j);
}
int main(int argc, const char * argv[]) {
    vector<vector<char>> board={{'.','.','9','7','4','8','.','.','.'},{'7','.','.','.','.','.','.','.','.'},{'.','2','.','1','.','9','.','.','.'},{'.','.','7','.','.','.','2','4','.'},{'.','6','4','.','1','.','5','9','.'},{'.','9','8','.','.','.','3','.','.'},{'.','.','.','8','.','3','.','2','.'},{'.','.','.','.','.','.','.','.','6'},{'.','.','.','2','7','5','9','.','.'}};
    solveSudoku(board);
    print_vec(board);
    return 0;
}

输出:

5 1 9 7 4 8 6 3 2 

7 8 3 6 5 2 4 1 9 

4 2 6 1 3 9 8 7 5 

3 5 7 9 8 6 2 4 1 

2 6 4 3 1 7 5 9 8 

1 9 8 5 2 4 3 6 7 

9 7 5 8 6 3 1 2 4 

8 3 2 4 9 1 7 5 6 

6 4 1 2 7 5 9 8 3 



你可能感兴趣的:(LeetCode,C++,backtracking)