这题不难,跟马的周游问题一样
开始没优化,就直接穷举(看到10秒嘛。。),结果TL,后来优化一下,对可能出现的数字少的点先进行枚举。
思路就这样,可是我做了四个小时。。。。。。。。。最后我认真认真的看一次题目,发现如果有多个解,solution要加s。。。。这基本的复数形式我错了。。。o(︶︿︶)o 唉
#include <iostream> #include <cstring> using namespace std; char a[9][9]; char tmp[9][9]; char first[9][9]; //the first solution bool isVisRow[9][9]; bool isVisCol[9][9]; bool isVisMatrix[3][3][9]; bool isFirst; int ans; int count[82]; void dfs() { int index = 81; for(int i = 0; i < 81; i++) { if(count[i] < count[index] && tmp[i / 9][i % 9] == '_') { index = i; } } if(index == 81) { if(isFirst) { memcpy(first, tmp, sizeof(tmp)); isFirst = false; } ans++; return; } int row = index / 9; int col = index % 9; for(int i = 0; i < 9; i++) { count[row * 9 + i]--; count[col + i * 9]--; } for(int i = 0; i < 9; i++) { if(!isVisRow[row][i] && !isVisCol[col][i] && !isVisMatrix[row / 3][col / 3][i]) { isVisRow[row][i] = true; isVisCol[col][i] = true; isVisMatrix[row / 3][col / 3][i] = true; tmp[row][col] = i + '1'; dfs(); tmp[row][col] = '_'; isVisRow[row][i] = false; isVisCol[col][i] = false; isVisMatrix[row / 3][col / 3][i] = false; } } for(int i = 0; i < 9; i++) { count[row * 9 + i]++; count[col + i * 9]++; } } void setCount() { memset(count, 0, sizeof(count)); for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { for(int k = 0; k < 9; k++) { if(!isVisRow[i][k] && !isVisCol[j][k] && !isVisMatrix[i / 3][j / 3][k]) count[i * 9 + j]++; } } } count[81] = 1000; } int main() { //freopen("1.txt", "r", stdin); int cases; cin >> cases; for(int k = 1; k <= cases; k++) { ans = 0; memset(isVisRow, false, sizeof(isVisRow)); memset(isVisCol, false, sizeof(isVisCol)); memset(isVisMatrix, false, sizeof(isVisMatrix)); isFirst = true; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { cin >> a[i][j]; tmp[i][j] = a[i][j]; if(a[i][j] != '_') { isVisRow[i][a[i][j] - '0' - 1] = true; isVisCol[j][a[i][j] - '0' - 1] = true; isVisMatrix[i / 3][j / 3][a[i][j] - '0' - 1] = true; } } } setCount(); dfs(); cout << "Puzzle " << k << " "; if(ans == 1) { cout << "solution is" << endl; for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) cout << first[i][j]; cout << endl; } }else if(ans == 0) cout << "has no solution" << endl; else cout << "has " << ans << " solutions" << endl; if(cases != k) cout << endl; } return 0; }
274

被折叠的 条评论
为什么被折叠?



