题意:数独
题解:dfs.dfs前判断能否填。
判断方法:用三个数组。
#define _CRT_SECURE_NO_WARNINGS #include<cstring> #include<cctype> #include<cstdlib> #include<cmath> #include<cstdio> #include<string> #include<stack> #include<ctime> #include<list> #include<set> #include<map> #include<queue> #include<vector> #include<sstream> #include<iostream> #include<functional> #include<algorithm> #include<memory.h> //#define INF 0x3f3f3f3f #define eps 1e-6 #define pi acos(-1.0) #define e exp(1.0) #define rep(i,t,n) for(int i =(t);i<=(n);++i) #define per(i,n,t) for(int i =(n);i>=(t);--i) #define mp make_pair #define pb push_back #define mmm(a,b) memset(a,b,sizeof(a)) //std::ios::sync_with_stdio(false); using namespace std; typedef long long ll; typedef unsigned long long ull; void smain(); #define ONLINE_JUDGE int main() { // ios::sync_with_stdio(false); #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); long _begin_time = clock(); #endif smain(); #ifndef ONLINE_JUDGE long _end_time = clock(); printf("time = %ld ms.", _end_time - _begin_time); #endif return 0; } int rowflag[9][10], colflag[9][10], blockflag[9][10]; int board[9][9]; struct pos { int r, c; pos(int rr, int cc) :r(rr), c(cc) {} }; vector<pos> blankpos; inline int GetBlockNum(int r, int c) { int rr = r / 3; int cc = c / 3; return rr * 3 + cc; } void SetAllFlags(int r, int c, int num, int f) { rowflag[r][num] = f; colflag[c][num] = f; blockflag[GetBlockNum(r, c)][num] = f; } bool isOK(int r, int c, int num) { return !rowflag[r][num] && !colflag[c][num] && !blockflag[GetBlockNum(r, c)][num]; } bool dfs(int n) {//处理前n个 if (n < 0) return 1; int r = blankpos[n].r; int c = blankpos[n].c; rep(num, 1, 9) { if (isOK(r, c, num)) { board[r][c] = num; SetAllFlags(r, c, num, 1); if (dfs(n - 1)) return 1; SetAllFlags(r, c, num, 0); } } return 0; } void Run() { mmm(rowflag, 0); mmm(colflag, 0); mmm(blockflag, 0); blankpos.clear(); rep(i, 0, 8)rep(j, 0, 8) { char c; cin >> c; board[i][j] = c - ‘0‘; if (board[i][j])SetAllFlags(i, j, board[i][j], 1); else blankpos.push_back(pos(i, j)); } if (dfs(blankpos.size()-1 ) ){ rep(i, 0, 8) { rep(j, 0, 8) cout <<char( board[i][j]+‘0‘); cout << endl; } } } void smain() { int t; cin >> t; while (t--) { Run(); } }
原文:https://www.cnblogs.com/SuuT/p/8982030.html