-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAI_Lab_3.cpp
More file actions
91 lines (74 loc) · 2.28 KB
/
AI_Lab_3.cpp
File metadata and controls
91 lines (74 loc) · 2.28 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
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int N = 8; // Number of queens
// Function to print the board
void printBoard(const vector<int>& board) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (board[i] == j)
cout << "Q ";
else
cout << ". ";
}
cout << endl;
}
cout << endl;
}
// Function to calculate the number of conflicts for a given board
int calculateConflicts(const vector<int>& board) {
int conflicts = 0;
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
if (board[i] == board[j] || abs(board[i] - board[j]) == j - i)
conflicts++;
}
}
return conflicts;
}
// Function to perform Hill Climbing
vector<int> hillClimbing() {
// srand(time(nullptr));
vector<int> currentBoard(N);
vector<int> nextBoard(N);
// Initialize the current board randomly
for (int i = 0; i < N; ++i) {
currentBoard[i] = rand() % N;
}
int currentConflicts = calculateConflicts(currentBoard);
while (currentConflicts > 0) {
int bestMoveConflicts = currentConflicts;
for (int i = 0; i < N; ++i) {
int originalColumn = currentBoard[i];
for (int j = 0; j < N; ++j) {
if (j != originalColumn) {
nextBoard = currentBoard;
nextBoard[i] = j;
int newConflicts = calculateConflicts(nextBoard);
if (newConflicts < bestMoveConflicts) {
bestMoveConflicts = newConflicts;
currentBoard = nextBoard;
}
}
}
}
if (bestMoveConflicts >= currentConflicts) {
// Local minimum reached, restart the search
for (int i = 0; i < N; ++i) {
currentBoard[i] = rand() % N;
}
currentConflicts = calculateConflicts(currentBoard);
} else {
currentConflicts = bestMoveConflicts;
}
}
return currentBoard;
}
int main() {
vector<int> solution = hillClimbing();
cout << "Solution found:" << endl;
printBoard(solution);
return 0;
}