51. N皇后
https://leetcode.cn/problems/n-queens/
N皇后有个特点便是,每一行有且只有一个皇后(在每一列也成立),所以我们可以分别在每一行放置皇后,判断某一行某个位置放置皇后是否和前面放置的皇后冲突,如果冲突就回溯,如果不冲突就进入下一行的递归
class Solution {
public:
vector<vector<string>> result;
bool isValid(int x, int y, int n, vector<string>& board) {
for (int i = 0; i < x; i++) {
if (board[i][y] == 'Q') return false;
}
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') return false;
}
for (int i = x - 1, j = y + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q') return false;
}
return true;
}
void backTracking(int x, int n, vector<string>& board) {
if (x == n) {
result.push_back(board);
return;
}
for (int j = 0; j < n; j++) {
if (!isValid(x, j, n, board)) continue;
board[x][j] = 'Q';
backTracking(x + 1, n, board);
board[x][j] = '.';
}
}
vector<vector<string>> solveNQueens(int n) {
result.clear();
vector<string> board(n, string(n, '.'));
backTracking(0, n, board);
return result;
}
};
37. 解数独
https://leetcode.cn/problems/sudoku-solver/
解数独和n皇后有一些相似之处,就是要一个棋盘上操作
在每一个空位上分别从1填到9看看是否和已经填好的冲突,如果冲突的话就回溯,不冲突的话就递归下一个位置
class Solution {
public:
bool isValidBoard(int row, int col, char val, vector<vector<char>>& board) {
for(int i = 0; i < 9; i++) {
if (board[row][i] == val) return false;
if (board[i][col] == val) return false;
}
int rowIdx = row - row % 3;
int colIdx = col - col % 3;
for (int i = rowIdx; i < rowIdx + 3; i++) {
for (int j = colIdx; j < colIdx + 3; j++) {
if (board[i][j] == val) return false;
}
}
return true;
}
bool backTracking(int row, int col, vector<vector<char>>& board){
if (row == 9) return true;
if (col == 9) {
return backTracking(row + 1, 0, board);
}
if (board[row][col] != '.') {
return backTracking(row, col + 1, board);
}
for (char i = '1'; i <= '9'; i++) {
if (!isValidBoard(row, col, i, board)) continue;
board[row][col] = i;
if (backTracking(row, col + 1, board)) return true;
board[row][col] = '.';
}
return false;
}
void solveSudoku(vector<vector<char>>& board) {
backTracking(0, 0, board);
}
};