[题目来源]:POJ2676
[关键字]:搜索
[题目大意]:完成一个数独(任意可行解)。
//============================================================================================================
[分析]:类似八皇后,只不过限制条件更多了,细心一点,注意一些技巧一次AC。对了,据说此题1 to 9循环比9 to 1循环,慢很多==
[代码]:
1 program Project1;
2 type
3 rec = record
4 x, y: longint;
5 end;
6 var
7 map: array[0..10,0..10] of longint;
8 a: array[0..90] of rec;
9 line, row, quee: array[0..10,0..10] of boolean;
10 tc, tot: longint;
11 goal: boolean;
12
13 function find(x, y: longint):longint;
14 begin
15 if ((1 <= x) and (x <= 3)) and ((1 <= y) and (y <= 3)) then exit(1);
16 if ((1 <= x) and (x <= 3)) and ((4 <= y) and (y <= 6)) then exit(2);
17 if ((1 <= x) and (x <= 3)) and ((7 <= y) and (y <= 9)) then exit(3);
18 if ((4 <= x) and (x <= 6)) and ((1 <= y) and (y <= 3)) then exit(4);
19 if ((4 <= x) and (x <= 6)) and ((4 <= y) and (y <= 6)) then exit(5);
20 if ((4 <= x) and (x <= 6)) and ((7 <= y) and (y <= 9)) then exit(6);
21 if ((7 <= x) and (x <= 9)) and ((1 <= y) and (y <= 3)) then exit(7);
22 if ((7 <= x) and (x <= 9)) and ((4 <= y) and (y <= 6)) then exit(8);
23 if ((7 <= x) and (x <= 9)) and ((7 <= y) and (y <= 9)) then exit(9);
24 end;
25
26 procedure init;
27 var
28 i, j, num, x: longint;
29 ch: char;
30 begin
31 fillchar(line,sizeof(line),true);
32 fillchar(row,sizeof(row),true);
33 fillchar(quee,sizeof(quee),true);
34 tot := 0;
35 for i := 1 to 9 do
36 begin
37 for j := 1 to 9 do
38 begin
39 read(ch);
40 x := ord(ch)-48;
41 map[i,j] := x;
42 if x = 0 then
43 begin
44 inc(tot);
45 a[tot].x := i;
46 a[tot].y := j;
47 end;
48 line[j,x] := false;
49 row[i,x] := false;
50 num := find(i,j);
51 quee[num,x] := false;
52 end;
53 readln;
54 end;
55 {for i := 1 to 9 do
56 for j := 1 to 9 do if not quee[i,j] then writeln(i,' ',j);}
57 end;
58
59 procedure dfs(k: longint);
60 var
61 i, x, y, num: longint;
62 begin
63 if k > tot then
64 begin
65 goal := true;
66 exit;
67 end;
68 for i := 9 downto 1 do
69 begin
70 x := a[k].x;
71 y := a[k].y;
72 num := find(x,y);
73 if (line[y,i]) and (row[x,i]) and (quee[num,i]) then
74 begin
75 map[x,y] := i;
76 line[y,i] := false;
77 row[x,i] := false;
78 quee[num,i] := false;
79 dfs(k+1);
80 if goal then exit;
81 line[y,i] := true;
82 row[x,i] := true;
83 quee[num,i] := true;
84 end;
85 end;
86 end;
87
88 procedure print;
89 var
90 i, j: longint;
91 begin
92 for i := 1 to 9 do
93 begin
94 for j := 1 to 9 do write(map[i,j]);
95 writeln;
96 end;
97 end;
98
99 begin
100 //assign(input,'d:\1.in');reset(input);
101 //assign(output,'d:\1.out');rewrite(output);
102 readln(tc);
103 while tc > 0 do
104 begin
105 init;
106 goal := false;
107 dfs(1);
108 print;
109 dec(tc);
110 end;
111 //close(input);
112 //close(output);
113 end.