Skip to content

Commit fe3ba6f

Browse files
authored
Merge pull request matthewsamuel95#1 from nonejk/backtracking
Added Backtracking algorithms
2 parents 44a9ecb + adc3283 commit fe3ba6f

File tree

2 files changed

+224
-0
lines changed

2 files changed

+224
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
#include <iostream>
2+
#define N 8
3+
using namespace std;
4+
5+
// defines a structure for chess moves
6+
typedef struct chess_moves {
7+
// 'x' and 'y' coordinates on chess board
8+
int x,y;
9+
}chess_moves;
10+
11+
// displays the knight tour solution
12+
void printTour(int tour[N][N]) {
13+
int i,j;
14+
for (i = 0; i < N; i++) {
15+
for (j = 0; j < N; j++) {
16+
cout<<tour[i][j]<<"\t";
17+
}
18+
cout<<endl;
19+
}
20+
}
21+
22+
// check if the next move (as per knight's constraints) is possible
23+
bool isMovePossible(chess_moves next_move, int tour[N][N]) {
24+
int i = next_move.x;
25+
int j = next_move.y;
26+
if ((i >= 0 && i < N) && (j >= 0 && j < N) && (tour[i][j] == 0))
27+
return true;
28+
return false;
29+
}
30+
31+
32+
// recursive function to find a knight tour
33+
bool findTour(int tour[N][N], chess_moves move_KT[],
34+
chess_moves curr_move, int move_count) {
35+
int i;
36+
chess_moves next_move;
37+
if (move_count == N*N-1) {
38+
// Knight tour is completed i.e all cells on the
39+
// chess board has been visited by knight once
40+
return true;
41+
}
42+
43+
// try out the possible moves starting from the current coordinate
44+
for (i = 0; i < N; i++) {
45+
// get the next move
46+
next_move.x = curr_move.x + move_KT[i].x;
47+
next_move.y = curr_move.y + move_KT[i].y;
48+
49+
if (isMovePossible(next_move, tour)) {
50+
// if the move is possible
51+
// increment the move count and store it in tour matrix
52+
tour[next_move.x][next_move.y] = move_count+1;
53+
if (findTour(tour, move_KT, next_move, move_count+1) == true) {
54+
return true;
55+
}
56+
else {
57+
// this move was invalid, try out other possiblities
58+
tour[next_move.x][next_move.y] = 0;
59+
}
60+
}
61+
}
62+
return false;
63+
}
64+
65+
// wrapper function
66+
void knightTour() {
67+
int tour[N][N];
68+
int i,j;
69+
70+
// initialize tour matrix
71+
for (i = 0; i < N; i++) {
72+
for (j = 0; j < N; j++) {
73+
tour[i][j] = 0;
74+
}
75+
}
76+
77+
// all possible moves that knight can take
78+
chess_moves move_KT[8] = { {2,1},{1,2},{-1,2},{-2,1},
79+
{-2,-1},{-1,-2},{1,-2},{2,-1} };
80+
81+
// knight tour starts from coordinate (0,0)
82+
chess_moves curr_move = {0,0};
83+
84+
// find a possible knight tour using a recursive function
85+
// starting from current move
86+
if(findTour(tour, move_KT, curr_move, 0) == false) {
87+
cout<<"Knight tour does not exist for the 8 x 8 board\n";
88+
}
89+
else {
90+
cout<<"Tour exists for the 8 x 8 board\n";
91+
printTour(tour);
92+
}
93+
}
94+
95+
// main
96+
int main() {
97+
knightTour();
98+
cout<<endl;
99+
return 0;
100+
}

BackTracking/NQueens/nqueens.c

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/* C/C++ program to solve n Queen Problem using
2+
backtracking */
3+
#include <stdio.h>
4+
#include <stdbool.h>
5+
int n;
6+
/* A utility function to print solution */
7+
void printSolution(int board[n][n])
8+
{
9+
static int k = 1;
10+
printf("%d-\n",k++);
11+
for (int i = 0; i < n; i++)
12+
{
13+
for (int j = 0; j < n; j++)
14+
printf(" %d ", board[i][j]);
15+
printf("\n");
16+
}
17+
printf("\n");
18+
}
19+
20+
/* A utility function to check if a queen can
21+
be placed on board[row][col]. note that this
22+
function is called when "col" queens are
23+
already placed in columns from 0 to col -1.
24+
So we need to check only left side for
25+
attacking queens */
26+
bool isSafe(int board[n][n], int row, int col)
27+
{
28+
int i, j;
29+
30+
/* Check this row on left side */
31+
for (i = 0; i < col; i++)
32+
if (board[row][i])
33+
return false;
34+
35+
/* Check upper diagonal on left side */
36+
for (i=row, j=col; i>=0 && j>=0; i--, j--)
37+
if (board[i][j])
38+
return false;
39+
40+
/* Check lower diagonal on left side */
41+
for (i=row, j=col; j>=0 && i<n; i++, j--)
42+
if (board[i][j])
43+
return false;
44+
45+
return true;
46+
}
47+
48+
/* A recursive utility function to solve n
49+
Queen problem */
50+
bool solvenQUtil(int board[n][n], int col)
51+
{
52+
/* base case: If all queens are placed
53+
then return true */
54+
if (col == n )
55+
{
56+
printSolution(board);
57+
return true;
58+
}
59+
60+
/* Consider this column and try placing
61+
this queen in all rows one by one */
62+
for (int i = 0; i < n; i++)
63+
{
64+
/* Check if queen can be placed on
65+
board[i][col] */
66+
if ( isSafe(board, i, col) )
67+
{
68+
/* Place this queen in board[i][col] */
69+
board[i][col] = 1;
70+
71+
/* recur to place rest of the queens */
72+
solvenQUtil(board, col + 1) ;
73+
74+
// below commented statement is replaced
75+
// by above one
76+
/* if ( solvenQUtil(board, col + 1) )
77+
return true;*/
78+
79+
/* If placing queen in board[i][col]
80+
doesn't lead to a solution, then
81+
remove queen from board[i][col] */
82+
board[i][col] = 0; // BACKTRACK
83+
}
84+
}
85+
86+
/* If queen can not be place in any row in
87+
this column col then return false */
88+
return false;
89+
}
90+
91+
/* This function solves the n Queen problem using
92+
Backtracking. It mainly uses solvenQUtil() to
93+
solve the problem. It returns false if queens
94+
canot be placed, otherwise return true and
95+
prints placement of queens in the form of 1s.
96+
Please note that there may be more than one
97+
solutions, this function prints one of the
98+
feasible solutions.*/
99+
void solvenQ()
100+
{
101+
int board[n][n];
102+
for(int i = 0; i < n; i++)
103+
for (int j = 0; j < n; ++j)
104+
{
105+
board [i] [j] = 0;
106+
}
107+
108+
if (solvenQUtil(board, 0))
109+
{
110+
printf("Solution does not exist\n");
111+
return ;
112+
}
113+
114+
return ;
115+
}
116+
117+
// driver program to test above function
118+
int main()
119+
{
120+
printf("Enter the size of the board, ie value of n:\n");
121+
scanf("%d",&n);
122+
solvenQ();
123+
return 0;
124+
}

0 commit comments

Comments
 (0)