HDU 1426 Sudoku Killer
7 1 2 ? 6 ? 3 5 8? 6 5 2 ? 7 1 ? 4? ? 8 5 1 3 6 7 29 2 4 ? 5 6 ? 3 75 ? 6 ? ? ? 2 4 11 ? 3 7 2 ? 9 ? 5? ? 1 9 7 5 4 8 66 ? 7 8 3 ? 5 1 98 5 9 ? 4 ? ? 2 3Sample Output
7 1 2 4 6 9 3 5 83 6 5 2 8 7 1 9 44 9 8 5 1 3 6 7 29 2 4 1 5 6 8 3 75 7 6 3 9 8 2 4 11 8 3 7 2 4 9 6 52 3 1 9 7 5 4 8 66 4 7 8 3 2 5 1 98 5 9 6 4 1 7 2 3Solution
记录每一个需要填补数字的位置,按顺序搜索判断行、列、格内是否符合即可
Code
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include <stack>#include <map>#include <vector>#include <queue>#define LL long longusing namespace std;int a[9][9], cnt, Case;int x[90], y[90], bj;char ch;inline bool pd(int num, int n) { for (int i = 0; i < 9; ++i) if (a[i][y[n]] == num || a[x[n]][i] == num) return false; int t1 = x[n] / 3 * 3; int t2 = y[n] / 3 * 3; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (a[t1 + i][t2 + j] == num) return false; return true;}inline void dfs(int n) { if (n > cnt) { for (int i = 0; i < 9; ++i) { for (int j = 0; j < 8; ++j) printf("%d ", a[i][j]); printf("%d/n", a[i][8]); } bj = 1; return ; } else for (int i = 1; i <= 9; ++i) if (!bj && pd(i, n)) a[x[n]][y[n]] = i, dfs(n + 1), a[x[n]][y[n]] = 0;}int main() { freopen("HDU1426.in", "r", stdin); freopen("HDU1426.out", "w", stdout); while (cin >> ch) { cnt = 0; if (ch == '?') a[0][0] = 0; else a[0][0] = ch - '0'; for (int i = 0; i < 9; ++i) for (int j = 0; j < 9; ++j) { if (!(i == 0 && j == 0)) cin >> ch; if (ch == '?') a[i][j] = 0, x[cnt] = i, y[cnt++] = j; else a[i][j] = ch - '0'; } cnt--, bj = 0; if (Case++) printf("/n"); dfs(0); } return 0;}Summary
输入的时候必须这么输
if (!(i == 0 && j == 0)) cin >> ch;
新闻热点
疑难解答