题目链接:HDU-5547 http://acm.hdu.edu.cn/showproblem.php?pid=5547
解题思想:随手练—— 数独 POJ - 2676 (回溯法+DFS)
HDU 的这题实在是太坑了,M 数组开成 int 就过不了,改成 char 就过了。对着别人AC的代码,一点点试,到最后才试出来,数组的问题,但是不能理解啊,什么鬼,这也错??
然后发现题目描述里有一句:Each test case starts with an empty line followed by 4 lines (输入样例里没有空行). 66666666666666666。告辞,我错了。
#include <iostream> #include <string> using namespace std; int M[4][4]; bool flag = false; int check(int row, int column, int x) { for (int i = 0; i < 4; i++) { if (M[i][column] == x || M[row][i] == x) return 0; } int r = row / 2 * 2, c = column / 2 * 2; for (int i = r; i < r + 2; i++) { for (int j = c; j < c + 2; j++) { if (M[i][j] == x) return 0; } } return 1; } void DFS(int row, int column) { if (row == 4) { flag = true; return; } if (M[row][column] == -6) { int i; for (i = 1; i <= 4; i++) { if (check(row, column, i)) { M[row][column] = i; DFS(row + (column + 1) / 4, (column + 1) % 4); if (flag) return; } } if (i == 5) { M[row][column] = -6; return; } } DFS(row + (column + 1) / 4, (column + 1) % 4); } int main() { int i = 1,n; cin >> n; string s; cin.ignore(); while (n--) { flag = false; for (int i = 0; i < 4; i++) { getline(cin, s); if (s.empty()) { i--; continue; } for (int j = 0; j < 4; j++) { M[i][j] = s[j]-‘0‘; } } DFS(0, 0); cout << "Case #" << i++ << ":" << endl; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { cout << M[i][j]; } cout << endl; } } return 0; }
原文地址:https://www.cnblogs.com/czc1999/p/10355018.html
时间: 2024-10-12 21:46:49