From 2e476852845fdfd17186c0a48b210ac7c8c8a06b Mon Sep 17 00:00:00 2001 From: Pritam <95082658+pritam1309@users.noreply.github.com> Date: Thu, 20 Oct 2022 21:47:39 +0530 Subject: [PATCH] =?UTF-8?q?Create=20The=20Knight=E2=80=99s=20tour=20proble?= =?UTF-8?q?m.cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- "The Knight\342\200\231s tour problem.cpp" | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 "The Knight\342\200\231s tour problem.cpp" diff --git "a/The Knight\342\200\231s tour problem.cpp" "b/The Knight\342\200\231s tour problem.cpp" new file mode 100644 index 0000000..ed5eea3 --- /dev/null +++ "b/The Knight\342\200\231s tour problem.cpp" @@ -0,0 +1,53 @@ +#include +#include +using namespace std; +#define N 5 +int row[] = { 2, 1, -1, -2, -2, -1, 1, 2, 2 }; +int col[] = { 1, 2, 2, 1, -1, -2, -2, -1, 1 }; + +bool isValid(int x, int y) +{ + if (x < 0 || y < 0 || x >= N || y >= N) { + return false; + } + + return true; +} + +void knightTour(int visited[N][N], int x, int y, int pos) +{ + visited[x][y] = pos; + if (pos >= N*N) + { + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) { + cout << visited[i][j] << " "; + } + cout << endl; + } + cout << endl; + visited[x][y] = 0; + return; + } + for (int k = 0; k < 8; k++) + { + int newX = x + row[k]; + int newY = y + col[k]; + if (isValid(newX, newY) && !visited[newX][newY]) { + knightTour(visited, newX, newY, pos + 1); + } + } + visited[x][y] = 0; +} + +int main() +{ + int visited[N][N]; + memset(visited, 0, sizeof visited); + + int pos = 1; + knightTour(visited, 0, 0, pos); + + return 0; +}