在刷 https://leetcode.cn/problems/sudoku-solver/description/ 遇到AddressSanitizer: heap-buffer-overflow
的报错。
代码为:
// 本题思路就是简单的回溯
// 注意限制:只有唯一解,限制了棋盘大小为9
class Solution {
public:
bool rowUsed[9][10];//标记每一行哪些数字用过了
bool colUsed[9][10];
bool kuaiUsed[3][3][10];
vector<vector<char>> res;
vector<vector<char>> board;
void getNext(int &row,int &col){
col++;
if(col==10){
row++;
col = 0;
}
}
void dfs(int row,int col){
cout<<"------"<<endl;
if(row ==9){
res = board;
return ;
}
while(board[row][col]!='.'){
getNext(row,col);
if(row ==9){
res = board;
return ;
}
}
int nextRow =row;
int nextCol = col+1;
if(nextCol == 10){
nextCol =0;nextRow++;
}
//填充当前位置
for(int num =1; num<=9 ;num++){
if(rowUsed[row][num]==false&&colUsed[col][num]==false&&kuaiUsed[row/3][col/3][num]==false){
rowUsed[row][num]=true;
colUsed[col][num]=true;
kuaiUsed[row/3][col/3][num]=true;
board[row][col]='0'+num;
dfs(nextRow,nextCol);
board[row][col]='.';
rowUsed[row][num]=false;
colUsed[col][num]=false;
kuaiUsed[row/3][col/3][num]=false;
}
}
}
void solveSudoku(vector<vector<char>>& board) {
this->board = board;
for(int i = 0;i<9;i++){
for(int j =0;j<9;j++){
if(board[i][j]!='.'){
int num = board[i][j]-'0';
rowUsed[i][num]=true;
colUsed[j][num]=true;
kuaiUsed[i/3][j/3][num]=true;
}
}
}
dfs(0,0);
board = this->res;
}
};
打印发现递归深度也非常浅,只有几层递归。输出如下:
------
------
------
------
------
------
------
------
------
------
------
后来只是简单的将全局变量board
,改成引用传递就可以了
// 本题思路就是简单的回溯
// 注意限制:只有唯一解,限制了棋盘大小为9
class Solution {
public:
bool rowUsed[9][10];//标记每一行哪些数字用过了
bool colUsed[9][10];
bool kuaiUsed[3][3][10];
vector<vector<char>> res;
void getNext(int &row,int &col){
col++;
if(col==10){
row++;
col = 0;
}
}
void dfs(int row,int col,vector<vector<char>>& board){
if(row ==9){
res = board;
return ;
}
while(board[row][col]!='.'){
getNext(row,col);
if(row ==9){
res = board;
return ;
}
}
int nextRow =row;
int nextCol = col+1;
if(nextCol == 10){
nextCol =0;nextRow++;
}
//填充当前位置
for(int num =1; num<=9 ;num++){
// rowUsed[i][num]=true;
// colUsed[j][num]=true;
// kuaiUsed[i/3][j/3][num]=true;
if(rowUsed[row][num]==false&&colUsed[col][num]==false&&kuaiUsed[row/3][col/3][num]==false){
rowUsed[row][num]=true;
colUsed[col][num]=true;
kuaiUsed[row/3][col/3][num]=true;
board[row][col]='0'+num;
dfs(nextRow,nextCol,board);
board[row][col]='.';
rowUsed[row][num]=false;
colUsed[col][num]=false;
kuaiUsed[row/3][col/3][num]=false;
}
}
}
void solveSudoku(vector<vector<char>>& board) {
for(int i = 0;i<9;i++){
for(int j =0;j<9;j++){
if(board[i][j]!='.'){
int num = board[i][j]-'0';
rowUsed[i][num]=true;
colUsed[j][num]=true;
kuaiUsed[i/3][j/3][num]=true;
}
}
}
dfs(0,0,board);
board = this->res;
}
};
不明白,因此请教大家。
标签:10,AddressSanitizer,buffer,int,board,heap,------,col,row From: https://www.cnblogs.com/swx123/p/17043372.html