# 2.process logic in current level (处理当前层逻辑) process(level, data, ...) # 3.drill down (下探到下一层) self.recursion(level + 1, p1, ...) # 4.reverse the current level status if needed (清理当前层)
private: voidsearch(std::string s, std::string& digits, int i, std::vector<std::string>& ans, std::unordered_map<char, std::string> map){ // terminator if (i == digits.size()) { ans.push_back(s); return; }
// process std::string letters = map.at(digits[i]); for (int j = 0; j < letters.size(); j++) { // drill down this->search(s+letters[j], digits, i+1, ans, map); } } };
defdfs(self, n, row, curr_state): # 终止条件 if row >= n: self.result.append(curr_state) return
# 当前层处理 for col inrange(n): if col in self.cols or row + col in self.pie or row - col in self.na: # 不能放 continue # 更新标志位 self.cols.add(col) self.pie.add(row + col) self.na.add(row - col)
def_generate_result(self, n): board = [] for res in self.result: for i in res: board.append("." * i + "Q" + "." * (n - i - 1)) return [board[i : i + n] for i inrange(0, len(board), n)]
voiddfs(std::vector<std::string>& curr_state, int row, int n){ // 终止条件 if (row == n) { m_ans.push_back(curr_state); return; }
// 循环每列, for (int col = 0; col < n; col++) { if (this->is_valid(curr_state, row, col)) { // doing curr_state[row][col] = 'Q'; // 下一行 this->dfs(curr_state, row + 1, n); // reverse curr_state[row][col] = '.'; } } }
boolis_valid(const std::vector<std::string>& curr_state, int row, int col){ int n = curr_state.size();
// 上 for (int i = 0; i < n; i++) { if (curr_state[i][col] == 'Q') { returnfalse; } }
// 左上 for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { if (curr_state[i][j] == 'Q') { returnfalse; } }
// 右上 for (int i = row, j = col; i >= 0 && j < n; i--, j++) { if (curr_state[i][j] == 'Q') { returnfalse; } }
// 其他方向都是未放过皇后的,不可能为false returntrue; }
};
写的很好的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: # 写的很好的python代码 defsolveNQueens(self, n: int) -> List[List[str]]: defdfs(queens, xy_dif, xy_sum): p = len(queens) if p == n: result.append(queens) returnNone for q inrange(n): if q notin queens and p-q notin xy_dif and p+q notin xy_sum: dfs(queens + [q], xy_dif+[p-q], xy_sum+[p+q]) result = [] dfs([], [], []) return [["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result]