-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab7.tar
More file actions
176 lines (128 loc) · 10 KB
/
Copy pathlab7.tar
File metadata and controls
176 lines (128 loc) · 10 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
nqueens.cpp 0000600 0065137 0016273 00000004036 14326127766 013026 0 ustar lsmit248 lsmit248 // Lab 7: N-queens using backtracking
/*Laura Smith 11:58 PM Lab 7 Part 1
This lab was to learn about recursion. We used a recursive statement to solve the nqueens problem, which is a problem
where on an nxn board how can you arrange chess queens so they all aren't in the line of fire of another. We used recursion
to go throuh all the possible boards and check if they were valid, printing only the valid boards.
*/
#include <iostream>
using namespace std;
//checks if a board is valid and returns as either true or false
bool valid (int board[], int size){
//double nested for loops that iterate through each possible combination of two spots on the board
//returns false if the two spots are in the same row, or if they are on the same slope, otherwise returns true
for (int i=0; i < size; i++){
for (int j= i + 1; j < size; j++){
int board_first = board[i];
int board_second = board[j];
if (board_first == board_second){
return false;
}
else if ((abs(board_first - board_second) == abs(i-j))){
return false;
}
}
}
return true;
}
//recursive function that takes an array, column number, and size of the board
void nqueens (int board[], int col, int size){
//if statement to check if a board is valid before continuing
if (valid (board, col-1)){
//prints out the board when the board is full
if (col == size){
if (valid (board, size)){
cout << board[0];
for (int i = 1; i < size; i++){
cout << ", " << board[i];
}
cout << endl;
}
}
//until the board is full runs the recursive statement to fill it
else {
for (int i = 0; i < size; i++){
board[col] = i;
nqueens (board, col+1, size);
}
}
}
}
int main(int argc, char *argv[]) {
int size = atoi (argv[1]); //reads in from the command line to get the size
int board[size]; //creates the board of the specified size
nqueens (board, 0, size); //begins the recursive function
return 0;
}