LeetCode 52. N皇后 II
這一週要準備位元組的面試,所以只貼程式碼,面試完之後補充完整
class Solution {
public:
void setZero(vector<vector<int>>& board, int layer, int col, int n) {
for (int i = 0; i < n; i++) {
board[layer][i] = 0;
board[i][col] = 0;
}
for (int i = 0; i + col < n && i + layer < n; i++)
board[layer + i][col + i] = 0;
for (int i = 0; col - i >= 0 && layer - i >= 0; i++)
board[layer - i][col - i] = 0;
for (int i = 0; i + col < n && layer - i >= 0; i++)
board[layer - i][col + i] = 0;
for (int i = 0; col - i >= 0 && layer + i < n; i++)
board[layer + i][col - i] = 0;
board[layer][col] = 9;
}
void move(vector<vector<int>> board, int& cnt, int layer, int n) {
for (int i = 0; i < n; i++) {
vector<vector<int>> hisBoard(board);
if (hisBoard[layer][i] == 1 && layer == n - 1) {
cnt++;
return;
}
else if (hisBoard[layer][i] == 1) {
setZero(hisBoard, layer, i, n);
//show(hisBoard);
move(hisBoard, cnt, layer + 1, n);
}
}
}
int totalNQueens(int n) {
int cnt = 0;
vector<vector<int>> board;
for (int i = 0; i < n; i++) {
vector<int> tmp(n, 1); //1代表可以落子
board.emplace_back(tmp);
}
//show(board);
move(board, cnt, 0, n);
return cnt;
}
};
相關文章
- 52. N皇后 II
- Leetcode每日一題:52.N-Queens II(N皇后Ⅱ)LeetCode每日一題
- Leetcode 通過率最高的困難題 N皇后 II 【回溯解法-剪枝】LeetCode
- N皇后和N皇后2
- [Hdfs] lc52. N皇后 II(dfs方案數+經典)
- N 皇后
- 51,N皇后
- N皇后問題
- 7-22 n queens (10分) 八皇后(n皇后)問題
- 藍橋杯-N皇后
- 20241201: 51. N 皇后
- leetcode演算法題解(Java版)-9-N皇后問題LeetCode演算法Java
- 演算法:N皇后二演算法
- 【一天一大 lee】N皇后 II (難度:困難) - Day20201017
- HDU - 2553 N皇后問題(DFS)
- [LeetCode] 158. Read N Characters Given Read4 II – Call multipleLeetCode
- 每日一題之拉低通過率 回溯演算法 leetcode 51 N皇后每日一題演算法LeetCode
- 2020-11-18 N皇后問題
- N皇后問題(各種優化)優化
- leetcode-90. Subsets IILeetCode
- Leetcode 40 Combination Sum IILeetCode
- Leetcode 213 House Robber IILeetCode
- LeetCode 1103[分糖果II]LeetCode
- 回溯法(排列樹)解決八(N)皇后問題
- [LeetCode] 210. Course Schedule IILeetCode
- [LeetCode] 305. Number of Islands IILeetCode
- [LeetCode] 212. Word Search IILeetCode
- [Leetcode]253. Meeting Rooms IILeetCodeOOM
- [LeetCode] 2105. Watering Plants IILeetCode
- [leetcode]linked-list-cycle-iiLeetCode
- leetcode 219. Contains Duplicate IILeetCodeAI
- [LeetCode] 910. Smallest Range IILeetCode
- [LeetCode] 45. Jump Game IILeetCodeGAM
- LeetCode-047-全排列 IILeetCode
- Leetcode 137. Single Number IILeetCode
- [LeetCode] 3152. Special Array IILeetCode
- n皇后問題--回溯法,以DFS的方式搜尋
- Leetcode 685. Redundant Connection II JavascriptLeetCodeJavaScript