题目:
要求把1-9填入九宫格中,各方向的和均相等。
分析:
这个程序最重要的是如何找到1-9填入九宫格的所有组合
代码:
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 | void grid_3x3() { long num=123456789; int count=0; int x1,y1,z1,x2,y2,z2,x3,y3,z3; for (;num<=987654321;num++) { z3=num%10; if (z3==0) continue ; y3=(num%100)/10; if (y3==0 || y3==z3) continue ; x3=(num%1000)/100; if (x3==0 || x3==y3 ||x3==z3) continue ; z2=(num%10000)/1000; if (z2==0 || z2==x3 || z2==y3 ||z2==z3) continue ; y2=(num%100000)/10000; if (y2==0 || y2 == z2 || y2==x3 || y2==y3 ||y2==z3) continue ; x2=(num%1000000)/100000; if (x2==0 || x2==y2 || x2 == z2 || x2==x3 || x2==y3 ||x2==z3) continue ; z1=(num%10000000)/1000000; if (z1==0 || z1==x2 || z1==y2 || z1 == z2 || z1==x3 || z1==y3 ||z1==z3) continue ; y1=(num%100000000)/10000000; if (y1==0 || y1 == z1 || y1==x2 || y1==y2 || y1 == z2 || y1==x3 || y1==y3 ||y1==z3) continue ; x1=(num%1000000000)/100000000; if (x1==0 || x1==y1|| x1 == z1 || x1==x2 || x1==y2 || x1 == z2 || x1==x3 || x1==y3 ||x1==z3) continue ; if (x1+y1+z1==x2+y2+z2 && x2+y2+z2==x3+y3+z3 && x3+y3+z3==x1+x2+x3 && x1+x2+x3==y1+y2+y3 && y1+y2+y3==z1+z2+z3 && z1+z2+z3==x1+y2+z3 && x1+y2+z3==x3+y2+z1) { count++; printf ( "-- %d --\n" ,count); printf ( "%d %d %d\n" ,x1,y1,z1); printf ( "%d %d %d\n" ,x2,y2,z2); printf ( "%d %d %d\n" ,x3,y3,z3); printf ( "\n" ); } } printf ( "Total: %d.\n" ,count); } |
输出:
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 | -- 1 -- 2 7 6 9 5 1 4 3 8 -- 2 -- 2 9 4 7 5 3 6 1 8 -- 3 -- 4 3 8 9 5 1 2 7 6 -- 4 -- 4 9 2 3 5 7 8 1 6 -- 5 -- 6 1 8 7 5 3 2 9 4 -- 6 -- 6 7 2 1 5 9 8 3 4 -- 7 -- 8 1 6 3 5 7 4 9 2 -- 8 -- 8 3 4 1 5 9 6 7 2 Total: 8. |