今天还行没看视频,自己直接写出来这两道难题,332重新安排行程就以后再说好了
题目链接:51.N皇后
class Solution {
public:
vector<vector<string>> result;
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n, string(n, '.'));
backtracking(board, 0, n);
return result;
}
void backtracking(vector<string>& board, int i, int n) {
if (n == 0) {
result.push_back(board);
return;
}
for (int j = 0; j < board.size(); j++) {
if (canPlace(board, i, j)) {
board[i][j] = 'Q';
backtracking(board, i + 1, n - 1);
board[i][j] = '.';
}
}
}
bool canPlace(vector<string>& board, int i, int j) {
for (int h = i; h >= 0; h--) {
if (board[h][j] != '.') return false;
}
for (int h = i, l = j; h >= 0 && l >= 0; h--, l--) {
if (board[h][l] != '.') return false;
}
for (int h = i - 1, l = j + 1; h >= 0 && l < board.size(); h--, l++) {
if (board[h][l] != '.') return false;
}
return true;
}
};
题目链接:37.解数独
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
bool is_full = false;
backtracking(board, 0, 0, is_full);
}
void backtracking(vector<vector<char>>& board, int i, int j, bool& is_full) {
if(i >= 9) {
is_full = true;
return;
}
if(board[i][j] != '.') {
if(j >= 8){
i++;
j = 0;
}
else j++;
if(i >= 9) {
is_full = true;
return;
}
backtracking(board, i, j, is_full);
return;
}
vector<bool> possible_vals = getPossibleVals(board, i, j);
for(int num = 0; num < 9; num++) {
if(possible_vals[num] == false) continue;
board[i][j] = '1' + num;
if(j >= 8)
backtracking(board, i + 1, 0, is_full);
else
backtracking(board, i, j + 1, is_full);
if(is_full) return;
board[i][j] = '.';
}
}
vector<bool> getPossibleVals(vector<vector<char>>& board, int i, int j) {
vector<bool> vals(9, true);
for(int h = 0; h < 9; h++) {
if(board[h][j] > '0' && board[h][j] <= '9') {
vals[board[h][j] - '0' - 1] = false;
}
}
for(int l = 0; l < 9; l++) {
if(board[i][l] > '0' && board[i][l] <= '9') {
vals[board[i][l] - '0' - 1] = false;
}
}
for(int h = i / 3 * 3; h < i / 3 * 3 + 3; h++) {
for(int l = j / 3 * 3; l < j / 3 * 3 + 3; l++) {
if(board[h][l] > '0' && board[h][l] <= '9') {
vals[board[h][l] - '0' - 1] = false;
}
}
}
return vals;
}
};