NYOJ 722 数独 (DFS)

来源:互联网 发布:小米电视软件安装 编辑:程序博客网 时间:2024/05/16 07:46


数独

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述

         数独是一种运用纸、笔进行演算的逻辑游戏。玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个3*3宫内的数字均含1-9,不重复。 每一道合格的数独谜题都有且仅有唯一答案,推理方法也以此为基础,任何无解或多解的题目都是不合格的。

       有一天hrdv碰到了一道号称是世界上最难的数独的题目,作为一名合格的程序员,哪能随随便便向困难低头,于是他决定编个程序来解决它。。


输入
第一行有一个数n(0< n <100),表示有n组测试数据,每组测试数据是由一个9*9的九宫格构成,0表示对应的格子为空
输出
输出一个9*9的九宫格,为这个数独的答案
样例输入
10 0 5 3 0 0 0 0 08 0 0 0 0 0 0 2 00 7 0 0 1 0 5 0 04 0 0 0 0 5 3 0 00 1 0 0 7 0 0 0 60 0 3 2 0 0 0 8 00 6 0 5 0 0 0 0 90 0 4 0 0 0 0 3 00 0 0 0 0 9 7 0 0
样例输出
1 4 5 3 2 7 6 9 8 8 3 9 6 5 4 1 2 7 6 7 2 9 1 8 5 4 3 4 9 6 1 8 5 3 7 2 2 1 8 4 7 3 9 5 6 7 5 3 2 9 6 4 8 1 3 6 7 5 4 2 8 1 9 9 8 4 7 6 1 2 3 5 5 2 1 8 3 9 7 6 4 
 #include <iostream>#include <cstring>#include <algorithm>using namespace std;int map[9][9];int flag;int t;int canD(int number, int x, int y){    for (int i = 0; i < 9; i++){        if (map[i][y] == number)            return 0;    }    for (int j = 0; j < 9; j++){        if (map[x][j] == number)            return 0;    }    int a = x / 3 * 3, b = y / 3 * 3;    for (int i = a; i < a + 3; i++){        for (int j = b; j < b + 3; j++){            if (map[i][j] == number)                return 0;        }    }    return 1;}void dfs(int x, int y){    if (flag)        return;    if (x == 9 && y == 0){        for (int i = 0; i < 9; i++){            for (int j = 0; j < 9; j++){                cout << map[i][j] << " ";            }            cout << endl;            flag = 1;        }        return;    }    if (y == 9)        dfs(x + 1, 0);    if (map[x][y] != 0)        dfs(x, y + 1);    if (map[x][y] == 0){        for (int i = 1; i <= 9; i++){            if (canD(i, x, y)){                map[x][y] = i;                dfs(x, y + 1);                map[x][y] = 0;            }        }    }}int main(){    cin >> t;    while (t--){        for (int i = 0; i < 9; i++){            for (int j = 0; j < 9; j++){                cin >> map[i][j];            }        }        dfs(0, 0);        flag = 0;    }    return 0;}        


0 0
原创粉丝点击