Skip to content

Instantly share code, notes, and snippets.

@YiqinZhao
Last active April 6, 2019 06:39
Show Gist options
  • Save YiqinZhao/4f44d4ffb5f48e5a5d1a132cbe26e331 to your computer and use it in GitHub Desktop.
Save YiqinZhao/4f44d4ffb5f48e5a5d1a132cbe26e331 to your computer and use it in GitHub Desktop.
8Queens in 10 Lines of C++
#include <iostream>
const int N = 8;
int queen[N];
bool check(int n) {
for (int i = 0; i < n; i++) {
int x = n - i;
int y = queen[n] - queen[i];
if (y == 0 || abs(x) == abs(y)) return false;
}
return true;
}
void dfs(int n) {
if (n == N) {
for (int i : queen)
std::cout << i << " ";
std::cout << std::endl;
}
for (int i = 0; i < N; i++) {
queen[n] = i;
if (check(n))
dfs(n + 1);
}
}
int main() {
dfs(0);
return 0;
}
#include <iostream>
int N = 8, queen[8];
int dfs(int n, int result = 0) {
if (n == N) return 1; else for (int i = 0, flag = 0; i < N; queen[n] = i, i++, result += (flag == 0 ? dfs(n + 1) : 0), flag = 0) for (int j = 0; j < n; j++) if (i - queen[j] == 0 || abs(n - j) == abs(i - queen[j])) flag = 1;
return result;
}
int main() {
std::cout << dfs(0) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment