codekofi
← All problems

Problem 30

Hard

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1void place(int n, int row, vector<int>& cols,
2 vector<vector<string>>& out) {
3
4 if (row == n) {
5
6 vector<string> board;
7
8 for (int c : cols) {
9 string line(n, '.');
10 line[c] = 'Q';
11 board.push_back(line);
12 }
13
14 out.push_back(board);
15 return;
16 }
17
18 for (int c = 0; c < n; c++) {
19
20 bool safe = true;
21
22 for (int r = 0; r < row; r++) {
23
24 int d = row - r;
25
26 if (cols[r] == c || cols[r] == c - d || cols[r] == c + d) {
27 safe = false;
28 break;
29 }
30 }
31
32 if (!safe) {
33 continue;
34 }
35
36 cols.push_back(c);
37 place(n, row + 1, cols, out);
38 cols.pop_back();
39 }
40}
41
42vector<vector<string>> solution(int n) {
43
44 vector<vector<string>> ans;
45 vector<int> cols;
46
47 place(n, 0, cols, ans);
48
49 return ans;
50}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.