数独c++

#include <bits/stdc++.h>
using namespace std;
const int maxn = 10;
bool maps[maxn][maxn], row[maxn][maxn], col[maxn][maxn];
int mat[maxn][maxn];
void print() {
    for (int i = 1; i <= 9; ++i) {
        for (int j = 1; j <= 9; ++j) {
            if (j != 1) cout << " ";
            cout << mat[i][j];
        }
        cout << endl;
    }
}
void dfs(int x, int y) {
    if (x > 9) {
        print();
        exit(0);
    }
    if (mat[x][y] != 0) {
        if (y == 9) dfs(x+1,1);
        else dfs(x,y+1);
    }
    else {
        for (int i = 1; i <= 9; ++i) {
            int k = (x-1)/3*3 + (y-1)/3 + 1;
            // 如果i这个数字没有被使用过
            if (!maps[k][i] && !row[x][i] && !col[y][i]) {
                mat[x][y] = i;
                maps[k][i] = row[x][i] = col[y][i] = true;
                if (y == 9) dfs(x+1,1);
                else dfs(x,y+1);
                mat[x][y] = 0;
                maps[k][i] = row[x][i] = col[y][i] = false;
            }
        }
    }
}
int main() {
    freopen("input.txt","r",stdin);
    for (int i = 1; i <= 9; ++i) {
        for (int j = 1; j <= 9; ++j) {
            cin >> mat[i][j];
            if (mat[i][j] == 0) continue;

            row[i][mat[i][j]] = true; // 第i行mat[i][j]被使用
            col[j][mat[i][j]] = true; // 第j列mat[i][j]被使用
            int k = (i-1)/3*3 + (j-1)/3 + 1;
            maps[k][mat[i][j]] = true; // 第k格mat[i][j]被使用
        }
    }
    cout << "原数独:" << endl;
    print();
    cout << "输出数独:" << endl;
    dfs(1,1);
    return 0;
}
posted @ 2020-05-01 17:44  麻辣猪仔  阅读(219)  评论(0)    收藏  举报