DFS POJ 2676 Sudoku
题意:数独问题,每行每列以及每块都有1~9的数字
分析:一个一个遍历会很慢。先将0的位子用vector存起来,然后用rflag[i][num] = 1 / 0表示在第i行数字num是否出现过,其他的类似,这样在用DFS就很快了,数据问题,反着搜索会更快。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | /************************************************ * Author :Running_Time * Created Time :2015/11/10 星期二 15:43:47 * File Name :POJ_2676.cpp ************************************************/ #include <iostream> #include <vector> #include <algorithm> #include <cstring> #include <cstdio> #include <cmath> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int N = 1e5 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; const double EPS = 1e-10; const double PI = acos (-1.0); struct Pos { int x, y; Pos () {} Pos ( int x, int y) : x (x), y (y) {} }; vector<Pos> blank; int mp[11][11]; int rflag[11][11], cflag[11][11], bflag[11][11]; int get_id( int x, int y) { int xx = x / 3; int yy = y / 3; return xx * 3 + yy; } void set_num( int x, int y, int num, int f) { rflag[x][num] = f; cflag[y][num] = f; bflag[get_id (x, y)][num] = f; } bool ok( int x, int y, int num) { return !rflag[x][num] && !cflag[y][num] && !bflag[get_id (x, y)][num]; } bool DFS( int cnt) { if (cnt < 0) return true ; int x = blank[cnt].x, y = blank[cnt].y; for ( int i=1; i<=9; ++i) { if (!ok (x, y, i)) continue ; mp[x][y] = i; set_num (x, y, i, 1); if (DFS (cnt - 1)) return true ; set_num (x, y, i, 0); } return false ; } int main( void ) { int T; scanf ( "%d" , &T); while (T--) { for ( int i=0; i<9; ++i) { for ( int j=0; j<9; ++j) { scanf ( "%1d" , &mp[i][j]); } } blank.clear (); memset (rflag, 0, sizeof (rflag)); memset (cflag, 0, sizeof (cflag)); memset (bflag, 0, sizeof (bflag)); for ( int i=0; i<9; ++i) { for ( int j=0; j<9; ++j) { if (mp[i][j] == 0) blank.push_back (Pos (i, j)); else { set_num (i, j, mp[i][j], 1); } } } if (DFS (blank.size () - 1)) { for ( int i=0; i<9; ++i) { for ( int j=0; j<9; ++j) { printf ( "%d" , mp[i][j]); } puts ( "" ); } } else puts ( "233" ); } //cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; return 0; } |
编译人生,运行世界!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步