1. 程式人生 > >HDU 1426(數獨 DFS)

HDU 1426(數獨 DFS)

code sin cin str truct close tar 完成 ...

題意是完成數獨。

記錄全圖,將待填位置處填 0,記錄下所有的待填位置,初始化結束。在每個待填位置處嘗試填入 1 - 9,若經過判斷後該位置可以填入某數字,則繼續向下填下一個位置,

回溯時把待填位置重新賦值為 0,總之就是深搜的思想。

要註意存數時是從 0 位置存到 8 位置,而不是從 1 位置存到 9 位置,因為這樣在後面判斷是否滿足 3*3 的小九宮格要求時可以直接用坐標乘以 3 再除以 3 的方法到達小九

宮格的左上角位置,便於遍歷小九宮格。

代碼如下:

技術分享圖片
  1 #include <bits/stdc++.h>
  2 using namespace std;
3 char c; 4 int cnt,cur,cas,f,mp[10][10]; 5 struct node 6 { 7 int x,y; 8 }q[90]; 9 10 bool judge(int n,int cur) 11 { 12 for(int i = 0; i < 9; ++i) 13 { 14 if(mp[q[cur].x][i] == n || mp[i][q[cur].y] == n) 15 return false; 16 } 17 int
x = q[cur].x/3*3; 18 int y = q[cur].y/3*3; 19 for(int i = 0; i < 3; ++i) 20 for(int j = 0; j < 3; ++j) 21 { 22 if(mp[x+i][y+j] == n) 23 return false; 24 } 25 return true; 26 } 27 28 void out() 29 { 30 for
(int i = 0; i < 9; ++i) 31 { 32 for(int j = 0; j < 9; ++j) 33 { 34 if(j) printf(" "); 35 printf("%d",mp[i][j]); 36 } 37 puts(""); 38 } 39 } 40 41 void dfs(int cur) 42 { 43 if(cur == cnt) 44 { 45 out(); 46 f = 1; 47 } 48 else 49 { 50 for(int i = 1; i <= 9&&!f; ++i) 51 { 52 if(judge(i,cur)) 53 { 54 mp[q[cur].x][q[cur].y] = i; 55 dfs(cur+1); 56 mp[q[cur].x][q[cur].y] = 0; 57 } 58 } 59 } 60 } 61 int main() 62 { 63 while(cin >> c) 64 { 65 cnt = 0; 66 if(c==?) 67 { 68 q[cnt].x = 0; 69 q[cnt++].y = 0; 70 mp[0][0] = 0; 71 } 72 else mp[0][0] = c-0; 73 for(int i = 1; i < 9; ++i) 74 { 75 cin >> c; 76 if(c==?) 77 { 78 q[cnt].x = 0; 79 q[cnt++].y = i; 80 mp[0][i] = 0; 81 } 82 else mp[0][i] = c-0; 83 } 84 for(int i = 1; i < 9; ++i) 85 for(int j = 0; j < 9; ++j) 86 { 87 cin >> c; 88 if(c==?) 89 { 90 q[cnt].x = i; 91 q[cnt++].y = j; 92 mp[i][j] = 0; 93 } 94 else mp[i][j] = c-0; 95 } 96 f = 0; 97 if(cas++) puts(""); 98 dfs(0); 99 100 } 101 return 0; 102 }
View Code

對於九宮格問題還可以用舞蹈鏈的方法,但水平有限,沒有掌握...... 有興趣者請移步:https://www.cnblogs.com/grenet/p/3163550.html

HDU 1426(數獨 DFS)