poj 2676 sudoku

题目来源:http://poj.org/problem?id=2676

跟http://blog.csdn.net/hearthougan/article/details/23038755一样,差别只在于输入输出!

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;


int Graph[10][10];
bool InputRow[10][10];
bool InputCol[10][10];
bool Grid[10][10];

bool DFS(int x, int y)
{
    if(x == 9)
        return true;
    if(Graph[x][y])
    {
        if(y == 8)
        {
            if(DFS(x+1, 0))
                return true;
            return false;
        }
        if(DFS(x, y+1))
            return true;
        return false;
    }

    for(int i = 1; i <= 9; ++i)
    {
        int k = 3 * (x/3) + (y/3);
        if(!InputRow[x][i] && !InputCol[y][i] && !Grid[k][i])
        {
            Graph[x][y] = i;
            InputRow[x][i] = true;
            InputCol[y][i] = true;
            Grid[k][i] = true;

            if(y == 8)
            {
                if(DFS(x+1, 0))
                    return true;
            }
            if(DFS(x, y+1))
                return true;

            Graph[x][y] = 0;
            InputRow[x][i] = false;
            InputCol[y][i] = false;
            Grid[k][i] = false;
        }
    }
    return false;
}


int main()
{
    char M[10][10];
    int T, i, j;
    scanf("%d", &T);
    while(T--)
    {
        memset(InputRow, false, sizeof(InputRow));
        memset(InputCol, false, sizeof(InputCol));
        memset(Grid, false, sizeof(Grid));
        for(i = 0; i < 9; ++i)
        {
            scanf("%s", M[i]);
            for(j = 0; j < 9; ++j)
            {
                Graph[i][j] = M[i][j] - '0';
                if(Graph[i][j])
                {
                    int k = 3 * (i/3) + (j/3);
                    InputRow[i][Graph[i][j]] = true;
                    InputCol[j][Graph[i][j]] = true;
                    Grid[k][Graph[i][j]] = true;
                }
            }
        }

        DFS(0, 0);

        for(i = 0; i < 9; ++i)
        {
            for(j = 0; j < 8; ++j)
                printf("%d", Graph[i][j]);
            printf("%d\n", Graph[i][j]);
        }
    }
    return 0;
}


你可能感兴趣的:(搜索,数独)