程序解数独


#include 
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */


bool line[9][9];
bool column[9][9];
bool block[3][3][9];
bool valid;
vectorint, int>> spaces;

void dfs(vectorchar>>& board, int pos) {
    if (pos == spaces.size()) {
        valid = true;
        return;
    }

    auto [i, j] = spaces[pos];
    for (int digit = 0; digit < 9 && !valid; ++digit) {
        if (!line[i][digit] && !column[j][digit] && !block[i / 3][j / 3][digit]) {
            line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
            board[i][j] = digit + '0' + 1;
            dfs(board, pos + 1);
            line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = false;
        }
    }
}

void solveSudoku(vectorchar>>& board) {
    memset(line, false, sizeof(line));
    memset(column, false, sizeof(column));
    memset(block, false, sizeof(block));
    valid = false;

    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 9; ++j) {
            if (board[i][j] == '.') {
                spaces.emplace_back(i, j);
            }
            else {
                int digit = board[i][j] - '0' - 1;
                line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
            }
        }
    }

    dfs(board, 0);
}

int main(int argc, char** argv) {
    vectorchar>> board(9);
    for(int i =0;i<9;i++)
        board.resize(9);
    cout<<"输入"<<endl;
    for(int i = 0;i<9;i++)
        for(int j = 0; j<9;j++)
            cin>>board[i][j];
    for(char row : board)
        for(int i =0;i<9;i++)
            cout<"\t";
        cout<<'\n';
    return 0;
}

相关