MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

cpp/Backtracking/n_queens.cpp:12–40  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10}
11
12void dfs(int r, std::set<int>& diagonalsSet, std::set<int>& antiDiagonalsSet, std::set<int>& colsSet, int n, int& res) {
13 // Termination condition: If we have reached the end of the rows,
14 // we've placed all 'n' queens.
15 if (r == n) {
16 res += 1;
17 return;
18 }
19 for (int c = 0; c < n; c++) {
20 int currDiagonal = r - c;
21 int currAntiDiagonal = r + c;
22 // If there are queens on the current column, diagonal, or
23 // anti-diagonal, skip this square.
24 if (colsSet.count(c) || diagonalsSet.count(currDiagonal) || antiDiagonalsSet.count(currAntiDiagonal)) {
25 continue;
26 }
27 // Place the queen by marking the current column, diagonal, and
28 // anti-diagonal as occupied.
29 colsSet.insert(c);
30 diagonalsSet.insert(currDiagonal);
31 antiDiagonalsSet.insert(currAntiDiagonal);
32 // Recursively move to the next row to continue placing queens.
33 dfs(r + 1, diagonalsSet, antiDiagonalsSet, colsSet, n, res);
34 // Backtrack by removing the current column, diagonal, and
35 // anti-diagonal from the sets.
36 colsSet.erase(c);
37 diagonalsSet.erase(currDiagonal);
38 antiDiagonalsSet.erase(currAntiDiagonal);
39 }
40}

Callers 1

nQueensFunction · 0.70

Calls 1

insertMethod · 0.45

Tested by

no test coverage detected