Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #define BOARD_SIZE 4
- #define DIRECTIONS 8
- #define UNVISITED -1
- using namespace std;
- int board[BOARD_SIZE][BOARD_SIZE];
- //int xDir[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
- //int yDir[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
- int xDir[] = { -1,-2, -2, -1, 1, 2, 1, 2 };
- int yDir[] = { -2,-1, 1, 2, -2, -1, 2, 1 };
- static int iterations = 5;
- void printBoard()
- {
- for (int i = 0; i < BOARD_SIZE; i++)
- {
- for (int j = 0; j < BOARD_SIZE; j++)
- {
- if(board[i][j] !=0)
- printf(" %02d", board[i][j]-4);
- else
- printf(" %02d", board[i][j]);
- }
- cout << endl;
- }
- }
- void initializeBoard()
- {
- for (int i = 0; i < BOARD_SIZE; i++)
- {
- for (int j = 0; j < BOARD_SIZE; j++)
- {
- board[i][j] = UNVISITED;
- }
- }
- board[0][0] = 0;
- board[0][3] = 0;
- board[3][3] = 0;
- board[3][0] = 0;
- }
- void printSolution()
- {
- cout << "Printing the solution" << endl;
- printBoard();
- }
- int isMovePossible(int x, int y)
- {
- if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
- return false;
- }
- else {
- cout << "The move is possible " << endl;
- return true;
- }
- }
- int solveProblem(int x, int y) {
- if (iterations == BOARD_SIZE * BOARD_SIZE)
- {
- return 1;
- }
- for (int i = 0; i < DIRECTIONS; i++)
- {
- int nextX = x + xDir[i];
- int nextY = y + yDir[i];
- if (isMovePossible(nextX, nextY) && board[nextX][nextY]== UNVISITED) {
- board[nextX][nextY] = iterations;
- iterations++;
- if (solveProblem(nextX, nextY)) {
- return true;
- }
- iterations--;
- board[nextX][nextY] = UNVISITED; //backtrack
- }
- }
- return false;
- }
- void solve()
- {
- board[0][2] = 0; // starting position 0,0
- if (solveProblem(0,2))
- {
- printSolution();
- }
- else
- {
- cout << "There are no solutions for this problem" << endl;
- printBoard();
- }
- }
- int main()
- {
- initializeBoard();
- solve();
- }
Advertisement
RAW Paste Data
Copied
Advertisement