-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonAttackingQueenPlacement.h
More file actions
64 lines (57 loc) · 1.51 KB
/
NonAttackingQueenPlacement.h
File metadata and controls
64 lines (57 loc) · 1.51 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
//
// NonAttackingQueenPlacement.h
// Recursion
//
// Created by shashank hegde on 12/19/15.
// Copyright (c) 2015 shashank hegde. All rights reserved.
//
#ifndef Recursion_NonAttackingQueenPlacement_h
#define Recursion_NonAttackingQueenPlacement_h
#include <iostream>
#include <vector>
using namespace std;
bool isValid(vector<int>* placements);
void solveNQueens(int n, int row, vector<int>* placements, vector<vector<int>>* result);
vector<vector<int>> nQueens(int n)
{
vector<int> placements;
vector<vector<int>> result;
solveNQueens(n, 0, &placements, &result);
return result;
}
void solveNQueens(int n, int row, vector<int>* placements, vector<vector<int>>* result)
{
if(row == n)
{
result->emplace_back(*placements);
}
else
{
for(int col=0; col < n; ++col)
{
placements->emplace_back(col);
if(isValid(placements))
{
solveNQueens(n, row+1, placements, result);
}
placements->pop_back();
}
}
}
// checking if the most recent placement is valid. The earlier values are valid only, else would have got popped.
bool isValid(vector<int>* placements)
{
size_t row_id = placements->size()-1;
for(size_t i=0; i <row_id; ++i)
{
int diff = abs((*placements)[i] - (*placements)[row_id]);
if(diff == 0 || // columns match
diff == (row_id-i) // same diagonal
)
{
return false;
}
}
return true;
}
#endif