[英]Segmentation fault: 11 of Maze problem in c++
迷宮由 2x2 向量表示,其中 0 表示阻塞,1 表示空閑單元。 目標是尋找起點和終點之間是否存在路徑,因此在判斷終點是否可以追溯到最后一點后,我嘗試遞歸該函數。 如果我訪問了每個點,我將點值更改為2,如果我訪問了起點,我將點值更改為3。最后,我檢查起點,如果是3,則返回true,否則返回false。 但它顯示了分段錯誤:11
如果我注釋掉代碼:
if(input[e.first+1][e.second] == 1 && e.first+1 < input[0].size()) {
if (e.first+1 == s.first && e.second == s.second){
input[e.first+1][e.second] = 3;
}else{
e.first += 1;
input[e.first][e.second] = 2;
maze(input, s, e);
}
}
答案是 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 2 0 0 0 0 2 2 2 2 2 1 3 1 0 0 2 0 1 1 1 2 2 0 0 1 2 2 0 0 1 2 2 2 2 2
功能:
bool Solution::maze(std::vector<std::vector<int>>& input, std::pair<int,int> s, std::pair<int,int> e){
input[.first][e.second] = 2;
if(e.first>=0 && e.second>=0 && e.first<input[0].size() && e.second<input.size()){
if(input[e.first][e.second-1] == 1 && e.second-1 >= 0){
if (e.first == s.first && e.second-1 == s.second){
input[e.first][e.second-1] = 3;
}else{
e.second -= 1;
input[e.first][e.second] = 2;
maze(input, s, e);
}
}
if(input[e.first+1][e.second] == 1 && e.first+1 < input[0].size()) {
if (e.first+1 == s.first && e.second == s.second){
input[e.first+1][e.second] = 3;
}else{
e.first += 1;
input[e.first][e.second] = 2;
maze(input, s, e);
}
}
if(input[e.first-1][e.second] == 1 && e.first-1 >= 0){
if (e.first-1 == s.first && s.second == e.second){
input[e.first-1][e.second] = 3;
}else{
e.first -= 1;
input[e.first][e.second] = 2;
maze(input, s, e);
}
}
if (input[e.first][e.second+1] == 1 && e.second+1 < input.size()){
if(e.first == s.first && e.second+1 == s.second){
input[e.first][e.second+1] = 3;
}else{
e.second += 1;
input[e.first][e.second] = 2;
maze(input, s, e);
}
}
}
if(input[s.first][s.second] == 3){
return true;
}else{
return false;
}
}
主功能:
int main() {
Solution solution;
std::vector<std::vector<int>> input = {{1, 1, 0, 0, 0},
{1, 1, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 0, 0, 0, 0},
{1, 1, 1, 1, 1}};
std::pair<int,int> s(1,2);
std::pair<int,int> e(4,4);
std::cout << solution.maze(input, s, e) << std::endl;
for(auto it = input.begin(); it != input.end(); ++it){
std::vector<int> n = *it;
for(auto it1 = n.begin(); it1 != n.end(); ++it1){
int n1 = *it1;
std::cout<< n1<< " ";
}
std::cout << std::endl;
}
std::vector<std::vector<int>> input1 = {{1, 1, 0, 0, 0},
{1, 0, 1, 1, 1},
{1, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{1, 1, 1, 1, 1}};
std::pair<int,int> s1(0,0);
std::pair<int,int> e1(4,4);
std::cout << solution.maze(input1, s1, e1) << std::endl;
for(auto it = input1.begin(); it != input1.end(); ++it){
std::vector<int> n = *it;
for(auto it1 = n.begin(); it1 != n.end(); ++it1){
int n1 = *it1;
std::cout<< n1<< " ";
}
std::cout << std::endl;
}
}
故障可能是由於您的數組循環之一調用了超出范圍的索引。 當您嘗試訪問 input[first][second] 並且其中一個像 input[first+1] 一樣遞增或遞減時,它可能超出范圍
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.