数独合理吗?(牛客数独板子)

数独合理吗?
依次遍历

#include <bits/stdc++.h>
using namespace std;

int a[10][10];
bool st[10];

void check(){
    for(int i = 1; i <= 9; ++i){
        for(int j = 1; j <= 9; ++j) st[a[i][j]] = true;

        int cnt = 0;
        for(int j = 0; j < 10; ++j) if(st[a[i][j]]) ++cnt;
        if(cnt != 9){
            cout << "NO" << endl; return;
        }
        memset(st, 0, sizeof st);
        for(int j = 1; j <= 9; ++j) st[a[j][i]] = true;
        cnt = 0;
        for(int j = 1; j <= 9; ++j) if(st[j]) ++cnt;
        if(cnt != 9){
            cout << "NO" << endl; return;
        }
        for(int l = 1; l <= 7; l += 3){
         for(int r = 1; r <= 7; r += 3){
            int sum = 0;
            for(int i = 0; i < 3; ++i){
                for(int j = 0; j < 3; ++j){
                    sum += a[l+i][j+r];
                }
            }
            if(sum != 45) {
                cout << "NO" << endl;
                return;
              }
            }
        }
 

        
    }
    
    cout << "YES" << endl;
    return;
}
signed main(){
    for(int i = 1; i <= 9; ++i){
        for(int j = 1; j <= 9; ++j){
            cin >> a[i][j];
        }
    }
    
    check();
    
    return 0;
}

简约版本

#include <bits/stdc++.h>

using  namespace std;

int a[10][10], row[10][10], col[10][10], box[4][4][10];

bool check(){
    memset(row, 0, sizeof row);memset(col, 0, sizeof col);memset(box, 0, sizeof box);
    for(int i = 0; i < 9; ++i){
        for(int j = 0; j < 9; ++j){
            int t = a[i][j]; 
            if(t <= 0 || t >= 10) return false;
            if(row[i][t]++) return false;
            if(col[j][t]++) return false;
            if(box[i/3][j/3][t]++) return false;
        }
    }
    return true;
}

signed main(){
    int N;
    cin >> N;

    while(N--){
        for(int i = 0; i < 9; ++i){
            for(int j = 0; j < 9; ++j){
                cin >> a[i][j];
            }
        }
    
        if(check()) cout << 1 << endl;
        else cout << 0 << endl;
    }

    return 0;
}
posted @ 2025-03-17 11:30  awei040519  阅读(6)  评论(0)    收藏  举报