题解 | #八皇后#回溯模板题,记住就行。

八皇后

https://www.nowcoder.com/practice/fbf428ecb0574236a2a0295e1fa854cb

//C++版代码
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
unordered_set<int> cols;
unordered_set<int> diag1;
unordered_set<int> diag2;
vector<int> ans;
void backtracking(int row, int result) {
    if (row == 8) {
        ans.push_back(result);
        return;
    }
    for (int i = 0; i < 8; i++) {
        if (cols.count(i) != 0) continue;
        if (diag1.count(row + i) != 0) continue;
        if (diag2.count(row - i) != 0) continue;
        cols.insert(i);
        diag1.insert(row + i);
        diag2.insert(row - i);
        backtracking(row + 1, result * 10 + i + 1);
        cols.erase(i);
        diag1.erase(row + i);
        diag2.erase(row - i);
    }
}
int main() {
    backtracking(0, 0);
    int b;
    while (cin >> b) {
        cout << ans[b - 1] << endl;
    }
    return 0;
}
//Java版代码
import java.util.*;
public class Main {
    private static Set<Integer> columns = new HashSet<>();
    private static Set<Integer> diagonals1 = new HashSet<>();
    private static Set<Integer> diagonals2 = new HashSet<>();
    private static List<Integer> ans = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        backtracking(0, 0);
        while (sc.hasNextInt()) {
            int b = sc.nextInt();
            System.out.println(ans.get(b - 1));
        }
    }
    private static void backtracking(int row, int result) {
        if (row == 8) {
            ans.add(result);
            return;
        }
        for (int i = 0; i < 8; i++) {
            if (columns.contains(i) || diagonals1.contains(row + i) || diagonals2.contains(row - i)) continue;
            columns.add(i);
            diagonals1.add(row + i);
            diagonals2.add(row - i);
            backtracking(row + 1, result * 10 + i + 1);
            columns.remove(i);
            diagonals1.remove(row + i);
            diagonals2.remove(row - i);
        }
    }
}
#Python版代码
def backtracking(row, result):
    if row == 8:
        ans.append(result)
        return
    for i in range(8):
        if i in columns or row - i in diagonals1 or row + i in diagonals2:
            continue
        columns.add(i)
        diagonals1.add(row - i)
        diagonals2.add(row + i)
        backtracking(row + 1, result * 10 + i + 1)
        columns.remove(i)
        diagonals1.remove(row - i)
        diagonals2.remove(row + i)
ans = []
columns = set()
diagonals1 = set()
diagonals2 = set()
backtracking(0, 0)
while True:
    try:
        print(ans[int(input()) - 1])
    except:
        break

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务