-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleApplication3.cpp
More file actions
93 lines (71 loc) · 1.38 KB
/
ConsoleApplication3.cpp
File metadata and controls
93 lines (71 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// KT
//
#include "stdafx.h"
#include <iostream>
#include <sstream>
using namespace std;
const int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
const int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
const int N = 8;
int startX, startY;
int board[N][N];
void getSize(){
string temp = "";
cout << "Enter X: ";
getline(cin, temp);
startX = std::stoi(temp);
cout << "Enter Y: ";
getline(cin, temp);
startY = std::stoi(temp);
}
void printBoard(){
for (int x = 0; x < N; x++){
for (int y = 0; y < N; y++){
printf(" %2d ", board[x][y]);
}
printf("\n");
}
}
bool isValid(int x, int y){
if ( x >= 0 && x < N && y >= 0 && y < N && board[x][y] == -1)
return true;
return false;
}
int solveBoard(int x, int y, int index){
int tempX, tempY;
if(index == N*N){
return true;
}
for(int i = 0; i < 8; i++){
tempX = x + xMove[i];
tempY = y + yMove[i];
if(isValid(tempX, tempY) == true){
board[tempX][tempY] = index;
if(solveBoard(tempX, tempY, index+1) == true){
return true;
} else {
board[tempX][tempY] = -1;
}
}
}
return false;
}
bool initBoard(){
for (int x = 0; x < N; x++){
for (int y = 0; y < N; y++){
board[x][y] = -1;
}
}
board[startX][startY] = 0;
if(solveBoard(startX, startY, 1) == false){
printf("failed");
return false;
} else {printBoard();}
return true;
}
int main(){
getSize();
initBoard();
getchar();
return 0;
}