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;
}
};
相關文章
- Leetcode每日一題:52.N-Queens II(N皇后Ⅱ)LeetCode每日一題
- Leetcode 通過率最高的困難題 N皇后 II 【回溯解法-剪枝】LeetCode
- N皇后問題
- 藍橋杯-N皇后
- 演算法:N皇后二演算法
- leetcode演算法題解(Java版)-9-N皇后問題LeetCode演算法Java
- N皇后問題(各種優化)優化
- Leetcode-Read N Characters Given Read4 IILeetCode
- 每日一題之拉低通過率 回溯演算法 leetcode 51 N皇后每日一題演算法LeetCode
- 回溯法(排列樹)解決八(N)皇后問題
- 經典n皇后問題java程式碼實現Java
- 用棧+回溯+非遞迴解決N皇后問題遞迴
- [LeetCode] 158. Read N Characters Given Read4 II – Call multipleLeetCode
- LeetCode-Read N Characters Given Read4 II - Call multiple timesLeetCode
- [LeetCode] Jump Game IILeetCodeGAM
- Leetcode jump Game IILeetCodeGAM
- Leetcode Spiral Matrix IILeetCode
- Leetcode Path Sum IILeetCode
- Leetcode-Subsets IILeetCode
- Leetcode-Permutations IILeetCode
- Leetcode Unique Paths IILeetCode
- Permutations II leetcode javaLeetCodeJava
- Subset II leetcode javaLeetCodeJava
- leetcode-90. Subsets IILeetCode
- Leetcode 213 House Robber IILeetCode
- LeetCode-Strobogrammatic Number IILeetCode
- LeetCode-Course Schedule IILeetCode
- LeetCode-H index IILeetCodeIndex
- LeetCode-Majority Element IILeetCode
- LeetCode-Basic Calculator IILeetCode
- LeetCode-Word Pattern IILeetCode
- LeetCode-Paint House IILeetCodeAI
- Leetcode: Arithmetic Slices II - SubsequenceLeetCode
- LeetCode 59 Spiral Matrix IILeetCode
- LeetCode-House Robber IILeetCode
- LeetCode-Number of Islands IILeetCode
- Leetcode-Word Break IILeetCode
- Leetcode-Path Sum IILeetCode