Last active
August 29, 2015 14:15
-
-
Save udonmai/b6c9b12cf22ef4ed9378 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <string> | |
using namespace std; | |
class Solution { | |
private: | |
bool checkDiagonal(vector<pair<int, int> > qv, pair<int, int> current) { | |
int length = qv.size(); | |
for (int i = 0; i < length; i++) { | |
if (abs(qv[i].first - current.first) == abs(qv[i].second - current.second)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
vector<string> toString(vector<pair<int, int> > qv, int n) { | |
string line(n, '.'); | |
vector<string> string_qv(n, line); | |
for (int i = 0; i < n; i++) { | |
string_qv[qv[i].first][qv[i].second] = 'Q'; | |
} | |
return string_qv; | |
} | |
void dfs(vector<vector<string> > &result, vector<pair<int, int> > qv, int counter, int visited[], int n) { | |
if (counter == n) { | |
result.push_back(toString(qv, n)); | |
} | |
for (int i = 0; i < n; i++) { | |
if (!visited[i] && checkDiagonal(qv, make_pair(counter, i))) { | |
visited[i] = 1; | |
qv.push_back(make_pair(counter, i)); | |
dfs(result, qv, counter + 1, visited, n); | |
visited[i] = 0; | |
qv.pop_back(); | |
} | |
} | |
} | |
public: | |
vector<vector<string> > solveNQueens(int n) { | |
vector<vector<string> > result; | |
vector<pair<int, int> > qv; | |
int counter = 0; | |
int visited[n]; | |
memset(visited, 0, sizeof(int)); | |
dfs(result, qv, counter, visited, n); | |
return result; | |
} | |
}; | |
int main(int argc, char const* argv[]) | |
{ | |
Solution s; | |
int n = 5; | |
vector<vector<string> > result = s.solveNQueens(n); | |
int number = result.size(); | |
for (int i = 0; i < number; i++) { | |
for (int j = 0; j < n; j++) { | |
cout << result[i][j] << endl; | |
} | |
cout << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment