主题:怎样验证9×9宫格内随机数字行和列不重复?
我是初学C#,写了个一个简单的代码,作用是将1~9数字随机分布在9×9的格子内(m,k是lable的坐标),现在我想实现行和列1~9不重复,就像数独那样,怎么实现呢?我的想法是里面再套个循环,遍历一下之前已经有的数字,如果发现没有,则正常输出,如果发现有了,则再random,直到不是重复的为止,但是不清楚怎么写。或者有没有其他的思路?谢谢大家!!
public Form1()
{
InitializeComponent();
Label[,] sudoku = new Label[9, 9];
int k = 25;
for (int i = 0; i < 9; i++)
{
int m = 98;
for (int j = 0; j < 9; j++)
{
sudoku[i, j] = new System.Windows.Forms.Label();
sudoku[i, j].Location = new System.Drawing.Point(m, k);
sudoku[i, j].BackColor = System.Drawing.Color.DarkGray;
sudoku[i, j].Size = new System.Drawing.Size(30, 30);
sudoku[i, j].BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
sudoku[i, j].Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
sudoku[i, j].TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
Random r = new Random();
int number = r.Next(1, 10);
sudoku[i, j].Text = number.ToString();
Controls.Add(sudoku[i, j]);
m = m + 30;
System.Threading.Thread.Sleep(100);
}
k = k + 30;
}
}
public Form1()
{
InitializeComponent();
Label[,] sudoku = new Label[9, 9];
int k = 25;
for (int i = 0; i < 9; i++)
{
int m = 98;
for (int j = 0; j < 9; j++)
{
sudoku[i, j] = new System.Windows.Forms.Label();
sudoku[i, j].Location = new System.Drawing.Point(m, k);
sudoku[i, j].BackColor = System.Drawing.Color.DarkGray;
sudoku[i, j].Size = new System.Drawing.Size(30, 30);
sudoku[i, j].BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
sudoku[i, j].Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
sudoku[i, j].TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
Random r = new Random();
int number = r.Next(1, 10);
sudoku[i, j].Text = number.ToString();
Controls.Add(sudoku[i, j]);
m = m + 30;
System.Threading.Thread.Sleep(100);
}
k = k + 30;
}
}