跳到正文

个人记录

数组模拟存图

gb_lw约 2 分钟
原文
文章信息与版本

文章信息

发布
2023年11月25日
收录
2026年7月2日
更新
2026年11月15日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
int n,m,u,y,v[100005],h[100005],vtx[100005],ntx[100005],idx=1;
void adde(int u,int v){
    vtx[idx]=v;
    ntx[idx]=h[u];
    h[u]=idx++;
}
void dfs(int x){
  v[x]=1;
  cout<<x<<' ';
  int it=h[x];
  while(it!=-1){
    if(!v[vtx[it]]){
      dfs(vtx[it]);
    }
    it=ntx[it];
  }
}
void bfs(){
  queue<int> q;
  q.push(1);
  v[1]=1;
  while(!q.empty()){
    int x=q.front();
    cout<<x<<' ';
    q.pop();
    int it=h[x];
    while(it!=-1){
      if(!v[vtx[it]]){
        v[vtx[it]]=1;
        q.push(vtx[it]);
      }
      it=ntx[it];
    }
  }
}
int main(){
  cin>>n>>m;
  memset(h,-1,sizeof(h));
  for(int i=1;i<=m;i++){
    cin>>u>>y;
    adde(u,y);
  }
  dfs(1);
  cout<<endl;
  memset(v,0,sizeof(v));
  bfs();
  return 0;
}
原文