事情是这样的:
这几天电脑不在手边,于是就在iPad文稿上写代码,写完复制到浏览器上一个在线编译器里。然后
问题就出现了。。
========================================================================
这是今天写的
```c++
#include
#include
using namespace std;
int n,m;
int used[51][51];
struct node{
int a;
int b;
};
queuepath;
int step;
node temp;
int next[4][2] = {{1,0},{-1,0},{0,-1},{0,1}};
void BFS(){
int a,b;
int flag = 1;
int rest = path.size();
int tn,tm;
while(flag){
if(rest==0){
step++;
rest = path.size();
}
if(rest==0) break;
a = path.front().a;
b = path.front().b;
for(int i = 0;i<4;i++){
tn = a+next[i][0];
tm = b+next[i][1];
if(tn<1||tn>n||tm<1||tm>n) continue;
if(used[tn][tm]==0){
if(tn==n&&tm==m){
step++;
flag = 0;
break;
}
temp.a = tn;
temp.b = tm;
path.push(temp);
}
}
rest--;
}
}
int main(){
cin >> n >> m;
for(int i = 1;i<=n;i++){
for(int j = 1;j<=m;j++){
cin >> used[i][j];
}
}
used[1][1] = 1;
temp.a = 1;
temp.b = 1;
path.push(temp);
BFS();
cout << step << endl;
return 0;
}
/*
用例
6 4
0 1 0 0
0 0 0 1
1 0 1 0
0 0 0 0
0 1 1 0
0 0 0 0
*/
========================================================================
这是昨天写的
```c++
#include
#include
using namespace std;
struct Map{
int place[2] = {};
int used;
int dire[2] = {};
int turn;
};
Map map[51][51];
int n,m;
queue
这是两道广搜算法的题,我都用了结构体来定义了队列,然后都出现了类似的报错
看上去好像都是队列出的问题,因为我定义的队列叫path
但是我也不知道具体是哪里有毛病
所以希望大家能帮我看看,谢谢🙏
1.不建议直接在浏览器的在线编辑器运行逻辑复杂的代码
2.这段代码出现了运行时错误(Segmentation fault),可能是因为程序访问了未分配的内存,或者数组越界;
3.试一下将数组used定义为[52][52],或者在读入数据时,使用下标从0开始的循环(for(int i = 0;i<n;i++)和for(int j = 0;j<m;j++))来遍历数组。
上面那个较下面少了一个队列pop()的函数,然后走过的点会重复加到队列中,造成队列过大,
谢谢三位 @程序yang @LiuJWo0 @programmer_ada
问题我都已经找到啦,第一段没有标记访问过的节点,第二段dire的迭代这部分没处理好