private void Button1_Click(object sender, EventArgs e) { int n; if (!CheckDataInput(out n)) { MessageBox.Show("Введено неверное значение. Введите 2, 4 или 6", "Ошибка ввода", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } dataGridView1.RowCount = n; dataGridView1.ColumnCount = n; for (int i = 0; i < n; i++) { dataGridView1.Columns[i].Width = 50; dataGridView1.Rows[i].Height = 50; } ; ClearCells(n); Matr mass = new Matr(n); Fishki fishki = new Fishki(); List <Index> index_list = new List <Index>(); MatrToGrid(n, mass); Main(ref mass, ref fishki, ref index_list); PaintCellAsync(index_list); }
static private bool IsFishkaExist(ref Fishki fishki, int value_1, int value_2) { foreach (Fishka fishka in fishki.Dibs) { if ((fishka.Value_1 == value_1 && fishka.Value_2 == value_2 && !fishka.IsUsed) || ((fishka.Value_1 == value_2 && fishka.Value_2 == value_1 && !fishka.IsUsed))) { fishka.IsUsed = true; return(true); } } return(false); }
private void Main(ref Matr mass, ref Fishki fishki, ref List <Index> index_list) { int i = 0; int j = 0; bool res = Domino.backtrack(i, j, ref mass, ref fishki, ref index_list); if (res) { textBox2.Text = "Успешно"; } else { textBox2.Text = "Неудача"; } }
static public bool backtrack(int i, int j, ref Matr mass, ref Fishki fishki, ref List <Index> index_list) { bool added = false; //Движение вправо if (j + 1 < mass.Size) { if (mass[i, j].IsUsed == false && mass[i, j + 1].IsUsed == false) { if (IsFishkaExist(ref fishki, mass[i, j].Value, mass[i, j + 1].Value) == true) { mass[i, j + 1].IsUsed = true; mass[i, j].IsUsed = true; index_list.Add(new Index(i, j, i, j + 1)); NextStep(mass); backtrack(x, y, ref mass, ref fishki, ref index_list); added = true; } } } //Движение влево if (j - 1 >= 0) { if (mass[i, j].IsUsed == false && mass[i, j - 1].IsUsed == false) { if (IsFishkaExist(ref fishki, mass[i, j].Value, mass[i, j - 1].Value) == true) { if (!added) { mass[i, j - 1].IsUsed = true; mass[i, j].IsUsed = true; } index_list.Add(new Index(i, j, i, j - 1)); NextStep(mass); backtrack(x, y, ref mass, ref fishki, ref index_list); added = true; } } } //Движение вверх if (i + 1 < mass.Size) { if (mass[i, j].IsUsed == false && mass[i + 1, j].IsUsed == false) { if (IsFishkaExist(ref fishki, mass[i, j].Value, mass[i + 1, j].Value) == true) { if (!added) { mass[i + 1, j].IsUsed = true; mass[i, j].IsUsed = true; } index_list.Add(new Index(i, j, i + 1, j)); NextStep(mass); backtrack(x, y, ref mass, ref fishki, ref index_list); added = true; } } } //Движение вниз if (i - 1 >= 0) { if (mass[i, j].IsUsed == false && mass[i - 1, j].IsUsed == false) { if (IsFishkaExist(ref fishki, mass[i, j].Value, mass[i - 1, j].Value) == true) { if (!added) { mass[i - 1, j].IsUsed = true; mass[i, j].IsUsed = true; } index_list.Add(new Index(i, j, i - 1, j)); NextStep(mass); backtrack(x, y, ref mass, ref fishki, ref index_list); added = true; } } } if (IsAllCellsFill(mass)) { return(true); } return(false); }