图的遍历,BFS中入队前忘了判断是否已入队,导致无限入队,直到内存超限,调试时会直接跳过这段代码,然后就卡住不动,找这个错误花了很长时间。。。。
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
int N;
vector<vector<int> > graph;
//返回图有几个连通分量
int BFS();
//计算n号顶点的最大深度
int depthCal(int n);
//当前访问的是v,深度dep,比较判断是否更新max_dep
void DFS(int v, int dep, int &max_dep, bool vis[]);
bool isLeaf(int v, bool vis[]);
int main(){
scanf("%d", &N);
graph.resize(N+1);
int depth[N+1];
int l = N-1;
while(l--){
int v1, v2;
scanf("%d%d", &v1, &v2);
graph[v1].push_back(v2);
graph[v2].push_back(v1);
}
//判断是否是树,题目设定为一定是N-1条边,只有一个连通分量的一定是树
int components = BFS();
if(components>1){
printf("Error: %d components", components);
}
else{
int max_d = 0;
for(int i=1; i<=N; i++){
depth[i] = depthCal(i);
if(depth[i]>max_d) max_d = depth[i];
}
for(int i=1; i<=N; i++){
if(depth[i]==max_d) printf("%d\n", i);
}
}
return 0;
}
int BFS(){
int c_count = 0;
bool inq[N+1] = {};
for(int k=1; k<=N; k++){
if(!inq[k]){
c_count++;
queue<int> q;
q.push(k);
inq[k] = true;
while(!q.empty()){
int v = q.front();
q.pop();
int n = graph[v].size();
for(int i=0; i<n; i++){
if(inq[graph[v][i]]) continue; //忘记这一句就会一直入队,内存超限
q.push(graph[v][i]);
inq[graph[v][i]] = true;
}
}
}
}
return c_count;
}
int depthCal(int n){
bool visited[N+1] = {};
int max_depth = 0;
DFS(n, 1, max_depth, visited);
return max_depth;
}
void DFS(int v, int dep, int &max_dep, bool vis[]){
vis[v] = true;
if(isLeaf(v, vis)){
if(dep>max_dep) max_dep = dep;
return;
}
int n = graph[v].size();
for(int i=0; i<n; i++){
if(vis[graph[v][i]]) continue;
DFS(graph[v][i], dep+1, max_dep, vis);
}
return;
}
bool isLeaf(int v, bool vis[]){
int n = graph[v].size();
for(int i=0; i<n; i++){
if(vis[graph[v][i]]==false) return false;
}
return true;
}
在进行图的BFS遍历时,由于忽视了在入队前检查节点是否已存在队列中,导致了无限循环并最终引发内存超限。这个问题在调试时尤为棘手,因为错误发生后调试器会直接跳过这段代码,使得定位问题变得困难。
655

被折叠的 条评论
为什么被折叠?



