알고리즘

[알고리즘] 백준 2239 - 스도쿠

blueberrysoda 2024. 7. 25. 21:22
#include <iostream>
using namespace std;

int Arr[10][10];

bool check(int y, int x, int k){
    for(int i=0; i<9; i++){
        if(Arr[y][i] == k){
            return false;
        }
        if(Arr[i][x] == k){
            return false;
        }
    }

    int a = y / 3;
    int b = x / 3;
    
    for(int i=0; i<3; i++){
        for(int j=0; j<3; j++){
            if(Arr[a * 3 + i][b * 3 + j] == k){
                return false;
            }
        }
    }
    return true;
}

void solve(int cnt){
    int y = cnt / 9;
    int x = cnt % 9;

    if(cnt == 81){
        for(int i=0; i<9; i++){
            for(int j=0; j<9; j++){
                cout << Arr[i][j];
            }
            cout << "\n";
        }
        exit(0);
    }

    if(Arr[y][x] == 0){
        for(int k=1; k<=9; k++){
            if(check(y, x, k) == true){
                Arr[y][x] = k;
                solve(cnt + 1);
                Arr[y][x] = 0;
            }
        }
    }
    else{
        solve(cnt + 1);
    }
    
    return;
}

int main(){
    string s;
    for(int i=0; i<9; i++){
        cin >> s;
        for(int j=0; j<9; j++){
            Arr[i][j] = s[j] - '0';
        }
    }

    solve(0);

    return 0;
}