Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
自从2006年3月10日至11日的首届数独世界锦标赛以后,数独这项游戏越来越受到人们的喜爱和重视。
据说,在2008北京奥运会上,会将数独列为一个单独的项目进行比赛,冠军将有可能获得的一份巨大的奖品―――HDU免费七日游外加lcy亲笔签名以及同hdu acm team合影留念的机会。
所以全球人民前仆后继,为了奖品日夜训练茶饭不思。当然也包括初学者linle,不过他太笨了又没有多少耐性,只能做做最最基本的数独题,不过他还是想得到那些奖品,你能帮帮他吗?你只要把答案告诉他就可以,不用教他是怎么做的。
数独游戏的规则是这样的:在一个9×9的方格中,你需要把数字1-9填写到空格当中,并且使方格的每一行和每一列中都包含1-9这九个数字。同时还要保证,空格中用粗线划分成9个3×3的方格也同时包含1-9这九个数字。比如有这样一个题,大家可以仔细观察一下,在这里面每行、每列,以及每个3×3的方格都包含1-9这九个数字。
例题:
答案:
Input
本题包含多组测试,每组之间由一个空行隔开。每组测试会给你一个 9*9 的矩阵,同一行相邻的两个元素用一个空格分开。其中1-9代表该位置的已经填好的数,问号(?)表示需要你填的数。
Output
对于每组测试,请输出它的解,同一行相邻的两个数用一个空格分开。两组解之间要一个空行。
对于每组测试数据保证它有且只有一个解。
Sample Input
7 1 2 ? 6 ? 3 5 8
? 6 5 2 ? 7 1 ? 4
? ? 8 5 1 3 6 7 2
9 2 4 ? 5 6 ? 3 7
5 ? 6 ? ? ? 2 4 1
1 ? 3 7 2 ? 9 ? 5
? ? 1 9 7 5 4 8 6
6 ? 7 8 3 ? 5 1 9
8 5 9 ? 4 ? ? 2 3
Sample Output
7 1 2 4 6 9 3 5 8
3 6 5 2 8 7 1 9 4
4 9 8 5 1 3 6 7 2
9 2 4 1 5 6 8 3 7
5 7 6 3 9 8 2 4 1
1 8 3 7 2 4 9 6 5
2 3 1 9 7 5 4 8 6
6 4 7 8 3 2 5 1 9
8 5 9 6 4 1 7 2 3
Source
ACM暑期集训队练习赛(三)
思路:记录所有?的坐标和?个数,枚举每个?的值即可。
PS:读入是大坑!我因为读入TLE了4次,在自己机子上跑没问题,到OJ就T,翻了网上的代码用了这个奇葩的读入方式才AC的。
AC代码:
#include <cstdio> using namespace std; int map[10][10]; struct node { int x, y; }pos[85]; int cnt; bool first = 1; bool input() { char t[2]; cnt = 0; for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) { if (scanf("%s", t) == -1) return 0; if (t[0] == '?') { map[i][j] = 0; pos[cnt].x = i; pos[cnt].y = j; cnt++; } else map[i][j] = t[0] - '0'; } return 1; } bool check(int step, int num) { for (int i = 0; i < 9; i++) { if (map[i][pos[step].y] == num && i != pos[step].x) return 0; if (map[pos[step].x][i] == num && i != pos[step].y) return 0; } int groupx = pos[step].x / 3; int groupy = pos[step].y / 3; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (((groupx * 3 + i) != pos[step].x || (groupy * 3 + j) != pos[step].y) && map[groupx * 3 + i][groupy * 3 + j] == num) return 0; return 1; } bool dfs(int step) { if (step == cnt) return 1; for (int i = 1; i <= 9; i++) { if (!check(step, i)) continue; map[pos[step].x][pos[step].y] = i; if (dfs(step + 1)) return 1; map[pos[step].x][pos[step].y] = 0; } return 0; } void solve() { dfs(0); if (!first) printf("\n"); first = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 8; j++) printf("%d ", map[i][j]); printf("%d\n", map[i][8]); } } int main() { while (input()) solve(); return 0; }
0 条评论