Answer the question
In order to leave comments, you need to log in
How does this C++ program work?
I can't figure out how it works.
#include<iostream>
#include<stdio.h>
using namespace std;
bool P(int *X, int k, int y, int N) // Поиск позиции для ферзя
{
int i = 0;
while ((i<k) && (y != X[i]) && (abs(k - i) != abs(y - X[i]))) { i++; }
if (i == k)
return true;
else if (i != k)
return false;
else
return !true && !false;
}
void Backtracking(int k, int &Count, int N, int *X) // Поиск с возвратом позиций
{
int i, y;
for (y = 0; y<N; y++)
if (P(X, k, y, N))
{
X[k] = y;
if (k == N - 1) {
for (i = 0; i<N; i++) { cout << char('A' + i) << X[i] + 1 << " "; }
cout << endl;
Count++;
}
Backtracking(k + 1, Count, N, X);
}
}
int main()
{
setlocale(LC_ALL, "Rus");
int N, Count = 0;
printf ("Введите количество ферзей \n N= ");
scanf_s ("%i", &N);
int *X = new int[N];
for (int i = 0; i<N; i++)
X[i] = 0;
printf("Расстановки %d ферзей: \n", N);
printf("На доске %d на %d \n", N, N);
Backtracking(0, Count, N, X);
printf("Всего расстановок: %d \n", Count);
delete[]X;
system("pause");
}
Answer the question
In order to leave comments, you need to log in
This is a common curriculum and I would beat hands for such code. Complaints to her.
1. Simultaneous use of printf and cout. However, despite the buggy, printf is a good thing, I myself made a more powerful analogue.
2. There are few cases where such variable/function names are acceptable.
• for the loop counter (i, j, k for a variable, it, jt, kt for an iterator, u, v, w for the new C++11 feature — what the iterator points to);
• if we convert a scientific article into code, and the variables are so named in the article.
3. Even the name Count is too vague - something like nFound is better.
UPD2. 4. I would rewrite the function P so that for [0...horizontal), when fighting return false, the cycle was successful - return true.
5. Shitcode Museum!
if (i == k)
return true;
else if (i != k)
return false;
else
return !true && !false;
void Backtracking(int currX, int &nFound, int boardSize, int queenY[])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question