Created
March 30, 2023 13:18
-
-
Save ijo42/10db1b20e252d10855605194de4a8155 to your computer and use it in GitHub Desktop.
задача о ходе коня
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
#include <random> | |
#include <fstream> | |
using namespace std; | |
/* Мальцев Александр КМБ-1 */ | |
/* задача о ходе коня */ | |
const int dX[] = {-2, -1, 1, 2, 2, 1, -1, -2}, | |
dY[] = {-1, -2, -2, -1, 1, 2, 2, 1}; | |
int **h, n; | |
void printArr(int **arr) { // вывод массива n * m в таблицу | |
for (int i = 0; i < n; ++i) { | |
for (int j = 0; j < n; ++j) { | |
cout << arr[i][j] << "\t"; | |
} | |
cout << "\n"; | |
} | |
} | |
bool tryPossible(long k, int x, int y) { | |
if (k > n * n) { | |
return true; | |
} | |
int u, v, i = 0; | |
do { | |
u = x + dX[i]; | |
v = y + dY[i]; | |
i++; | |
if (((0 <= u && u < n) && (0 <= v && v < n)) && h[u][v] == 0) { | |
h[u][v] = k; | |
if (k <= n * n) { | |
if (tryPossible(k + 1, u, v)) { | |
return true; | |
} else { | |
h[u][v] = 0; | |
} | |
} | |
} | |
} while (i != 8); | |
return false; | |
} | |
int main() { | |
cout.precision(2); | |
cout.setf(ios_base::fixed); | |
cout << "n="; | |
cin >> n; | |
h = new int *[n]; // иницилизация массива указателей | |
for (int i = 0; i < n; ++i) { // иницилизация массивов для строк | |
h[i] = new int[n]; | |
} | |
int x, y; | |
cout << "x="; | |
cin >> x; | |
cout << "y="; | |
cin >> y; | |
h[x][y] = 1; | |
if (!tryPossible(2, x, y)) { | |
cout << "\nНевозможно создать маршрут\n"; | |
} else { | |
printArr(h); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment