ACM篇:POJ 2676 -- Sudoku

简单粗暴的深搜。

#include <iostream>
#include <cstdio>
#include <vector>
#include <cctype>
using namespace std;
const int N = 9;

int board[N][N];
struct Point
{
    int r;
    int c;
    Point(int r=0, int c=0)
    {
        this->r = r;
        this->c = c;
    }
};
vector<Point>pot;
void read_board()
{
    int ch;

    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
        {
            while (!isdigit(ch=getchar()))
                ;
            board[i][j] = ch - '0';
        }
}

int init_empty()
{   
    pot.clear();
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
        {
            if (!board[i][j])
                pot.push_back(Point(i, j));
        }
    return pot.size();
}

bool is_ok(int x, int r, int c)
{
    for (int i = 0; i < N; i++)
        if (board[r][i] == x || board[i][c] == x)
            return false;

    r = r / 3 * 3; 
    c = c / 3 * 3;

    for (int i = r; i < r + 3; i++)
        for (int j = c; j < c + 3; j++)
        {
            if (board[i][j] == x)
                return false;
        }
    return true;
}
bool fill_empty(int cnt, int tot)
{
    if (cnt >= tot)
        return true;

    int r = pot[cnt].r;
    int c = pot[cnt].c;

    for (int i = 1; i <= N; i++)
    {
        if (is_ok(i, r, c))
        {
            board[r][c] = i;
            if(fill_empty(cnt+1, tot))
                return true;
            board[r][c] = 0;
        }
    }   
    return false;
}

void print_board()
{
    for (int i = 0; i < N; i++)
    {
        putchar('\n');
        for (int j = 0 ; j < N; j++)
            printf("%d", board[i][j]);
    }
}
int main()
{
    int T;
    int tot;
    scanf("%d", &T);

    while (T-- > 0)
    {
        read_board();
        tot = init_empty();
        fill_empty(0, tot);
        print_board();
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值