九宫格(数独)生成

控制台生成九宫格(数独):

 
  
1 using System;
2   using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Sudoku
7 {
8 class Program
9 {
10 static int [,] grid = new int [ 9 , 9 ]; // 九宫格的81个格子。
11 static bool got = false ; // 如果找到一个方案,则设置为true。
12 static Random random = new Random(); // 用于生成随机数。
13
14 static void Main( string [] args)
15 {
16 while ( true )
17 {
18 got = false ;
19 FillCell( 0 , 0 );
20 if (System.Console.ReadKey().Key == System.ConsoleKey.Escape)
21 {
22 return ;
23 }
24 }
25 }
26
27 static void Print() // 控制台打印。
28 {
29 for ( int row = 0 ; row < 9 ; row ++ )
30 {
31 for ( int col = 0 ; col < 9 ; col ++ )
32 {
33 System.Console.Write( " {0} " , grid[row, col]);
34 }
35 System.Console.WriteLine();
36 }
37 System.Console.WriteLine();
38 }
39
40 static List < int > GetRandomDigits() // 生产1-9的随机序列。
41 {
42 List < int > v = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
43 List < int > result = new List < int > ( 9 );
44 while (v.Count > 0 )
45 {
46 int index = random.Next( 0 , v.Count);
47 result.Add(v[index]);
48 v.RemoveAt(index);
49 }
50 return result;
51 }
52
53 static void FillCell( int row, int col) // row和col都是从0到8。
54 {
55 if (row >= 9 )
56 {
57 got = true ;
58 Print();
59 return ;
60 }
61 foreach (var x in GetRandomDigits()) // 填充在(row,col)单元格的数字x。
62 {
63 if ( ! IsRepeatInRow(row, col, x) && ! IsRepeatInColumn(row, col, x) && ! IsRepeatInBigCell(row, col, x)) // x在行、列及同一个大格中都不重复。
64 {
65 grid[row, col] = x;
66
67 FillCell(row + (col + 1 ) / 9 , (col + 1 ) % 9 );
68 // if (col == 8)
69 // {
70 // FillCell(row + 1, 0);
71 // }
72 // else
73 // {
74 // FillCell(row, col + 1);
75 // }
76 if (got) // 结束整个递归过程。
77 {
78 return ;
79 }
80 }
81 }
82 }
83
84 static bool IsRepeatInRow( int row, int col, int x) // 检查同一行中是否存在重复。
85 {
86 for ( int i = 0 ; i < col; i ++ )
87 {
88 if (grid[row, i] == x)
89 {
90 return true ;
91 }
92 }
93 return false ;
94 }
95
96 static bool IsRepeatInColumn( int row, int col, int x) // 检查同一列中是否存在重复。
97 {
98 for ( int i = 0 ; i < row; i ++ )
99 {
100 if (grid[i, col] == x)
101 {
102 return true ;
103 }
104 }
105 return false ;
106 }
107
108 static bool IsRepeatInBigCell( int row, int col, int x) // 检查同一个大格中是否存在重复。
109 {
110 for ( int i = (row / 3 ) * 3 ; i < row; i ++ )
111 {
112 for ( int j = col - col % 3 ; (j < col + 3 - col % 3 ) && (j != col); j ++ ) // IsRepeatInColumn(row, col, x)已经包含列的比较。
113 {
114 if (grid[i, j] == x)
115 {
116 return true ;
117 }
118 }
119 }
120 for ( int j = 0 ; j < col; j ++ ) // 可省略,IsRepeatInRow(row, col, x)已经包含。
121 {
122 if (grid[row, j] == x)
123 {
124 return true ;
125 }
126 }
127 return false ;
128 }
129 }
130 }

转载于:https://www.cnblogs.com/liumeibiao/archive/2011/02/15/1955588.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值