From ca510e0f9f3da8560ac72a4c80b33b167582e5e5 Mon Sep 17 00:00:00 2001 From: Andrew Guschin Date: Wed, 27 Apr 2022 13:46:41 +0400 Subject: =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=B0?= =?UTF-8?q?=D0=BB=D0=B3=D0=BE=D1=80=D0=B8=D1=82=D0=BC=20=D0=BE=D0=B1=D1=85?= =?UTF-8?q?=D0=BE=D0=B4=D0=B0=20=D0=BA=D0=BE=D0=BD=D1=91=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 9 +++++ knights-tour.cpp | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 Makefile create mode 100644 knights-tour.cpp diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..7e36cc1 --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +CXX=g++ +CXXFLAGS=-Wall -Wpedantic -ggdb -std=c++17 +SOURCES := $(wildcard *.cpp) +EXECS := $(patsubst %.cpp,%.out,$(SOURCES)) + +all: $(EXECS) + +%.out: %.cpp + $(CXX) $(CXXFLAGS) $< -o $@ diff --git a/knights-tour.cpp b/knights-tour.cpp new file mode 100644 index 0000000..3f1e674 --- /dev/null +++ b/knights-tour.cpp @@ -0,0 +1,106 @@ +#include +#include +#include + +typedef std::vector> field_t; +struct point_t { int row, col; }; + +int n; +int row, col; +field_t field; + +std::vector +neighbors(int row, int col) +{ + std::vector v; + std::vector possible = { + { row - 2, col - 1 }, + { row - 1, col - 2 }, + { row + 1, col - 2 }, + { row + 2, col - 1 }, + { row - 2, col + 1 }, + { row - 1, col + 2 }, + { row + 1, col + 2 }, + { row + 2, col + 1 }, + }; + + for (point_t p : possible) + { + if (p.row >= 0 && p.row < n && + p.col >= 0 && p.col < n) + { + v.push_back(p); + } + } + + return v; +} + +bool +tour(int row, int col, int step, field_t field, field_t &result) +{ + for (point_t p : neighbors(row, col)) + { + if (field[p.row][p.col] != 0) continue; + field[p.row][p.col] = step; + + if (step == n * n) + { + result = field; + return true; + } + if (tour(p.row, p.col, step + 1, field, result)) + { + return true; + } + field[p.row][p.col] = 0; + } + return false; +} + +int +main() +{ + std::cout << "Размер поля (n): "; + std::cin >> n; + + std::cout << "Положение коня (ряд, колонка): "; + std::cin >> row >> col; + row--; + col--; + + field = std::vector(n, std::vector(n)); + field[row][col] = 1; + + field_t result(n, std::vector(n)); + bool found = tour(row, col, 2, field, result); + + int width = 0; + { + int q = n * n; + while (q > 0) + { + width++; + q /= 10; + } + } + + if (found) + { + std::cout << "Обход конём найден:" << std::endl; + for (int i = 0; i < n; ++i) + { + for (int j = 0; j < n; ++j) + { + std::cout << std::setw(width + 1) << result[i][j]; + if (j < n - 1) std::cout << ' '; + } + if (i < n - 1) std::cout << '\n'; + } + std::cout << std::endl; + } + else + { + std::cout << "Обход конём не найден" << std::endl; + } +} -- cgit v1.2.3