poj2676 Sudoku 数独

记录所有空位置,三个数组(row[M][M], col[M][M], mat[3][3][M])hash判断当前空位置是否可以填某个数,然后直接DFS,注意从后往前搜索,时间比正向搜快很多。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

#define M 11

struct point { int x, y; } p[100];
//row[i][j]表示第i行是否有数字j,col[i][j]表示第i列是否有数字j,mat[i][j][k]表示第(i,j)位置的小九宫格里是否有数字k
int map[M][M];
bool flag, row[M][M], col[M][M], mat[3][3][M];
int np;

void DFS(int num)
{
    if (flag) return;

    int i, j;

    if (num == -1) {
        for (i = 0; i < 9 && !flag; i++) {
            for (j = 0; j < 9; j++)
                printf ("%d", map[i][j]);
            printf ("\n");
        }
        flag = true;
        return;
    }

    for (i = 1; i <= 9 && !flag; i++) {
        int x = p[num].x;
        int y = p[num].y;
        if (!row[x][i] && !col[y][i] && !mat[x/3][y/3][i]) {
            row[x][i] = col[y][i] = mat[x/3][y/3][i] = true;
            map[x][y] = i;
            DFS(num-1);
            row[x][i] = col[y][i] = mat[x/3][y/3][i] = false;
            map[x][y] = 0;
        }
    }
}

int main()
{
    int t, i, j;

    scanf ("%d", &t);
    while (t--) {
        memset (row, false, sizeof (row));
        memset (col, false, sizeof (col));
        memset (mat, false, sizeof (mat));
        np = 0;
        for (i = 0; i < 9; i++) {
            for (j = 0; j < 9; j++) {
                scanf ("%1d", &map[i][j]);
                int num = map[i][j];
                if (num)
                    row[i][num] = col[j][num] = mat[i/3][j/3][num] = true;
                else {
                    p[np].x = i;
                    p[np++].y = j;
                }
            }
        }
        flag = false;
        DFS(np-1);
    }
    return 0;
}




你可能感兴趣的:(struct)