S
S
Shell1542018-06-12 12:37:00
C++ / C#
Shell154, 2018-06-12 12:37:00

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

1 answer(s)
M
Mercury13, 2018-06-12
@Mercury13

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;

Correct
The program goes through the 1st horizontal and places a queen on each cell. If it fits, it recursively does the same for the 2nd horizontal, if not, then it's out of luck. As soon as the calculation reaches the Nth horizontal, we have found the location of the queens, you can display.
UPD. Well, let's say I would rewrite the 2nd function like this (without changing the order of the parameters).
void Backtracking(int currX, int &nFound, int boardSize, int queenY[])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question