回溯法解决n皇后问题

    xiaoxiao2025-09-12  46

     

    //8_4 #include<iostream> #include<vector> using namespace std; int n = 8; vector <int> result(n), Left(2 * n + 1)/*左下线区域*/, Right(2 * n)/*右下线区域*/, visited(n);/*竖直区域*/ void dfs(int i) { if (i == n) { for (int j = 0; j < n; j++) cout << result[j] << " "; cout << endl; } for (int j = 0; j < n; j++) { if (!(Left[n+i-j] || Right[i+j] || visited[j])) { Left[n + i - j] = visited[j] = Right[i + j] = 1; result[i] = j; dfs(i + 1); Left[n + i - j] = visited[j] = Right[i + j] = 0; } } } int main() { int n; dfs(0); return 0; }

     

    最新回复(0)