不要拘泥于代码。把思路理清之后,试着自己写一遍。
详见注释。
邻接表——链表
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <stack>
#include <string>
#include <vector>
#pragma comment(linker, "/STACK:1024000000");
#define LL long long int
#define ULL unsigned long long int
#define _LL __int64
#define INF 0x3f3f3f3f
#define Mod 1000000009
using namespace std;
const int MAXN_Edge = 2000001;//边集大小
const int MAXN_Point = 1010;//点集大小
struct N
{
int u,v;//数据域
N *next;//用来记录下一个节点的位置
}*head[MAXN_Point];//头指针。head[i]上的节点存储着与 i 相连的点。
N *creat()//生成新的节点
{
N *p = (N *)malloc(sizeof(N));
p->next = NULL;
return p;
}
void Link(int u,int v)//将 v 链接到 head[u] 上。
{
N *p = creat();
p->u = u;
p->v = v;
p->next = head[u]->next;
head[u]->next = p;
}
bool mark[MAXN_Point];
void bfs(int n)
{
queue<int> q;
memset(mark,false,sizeof(mark));
mark[n] = true;
q.push(n);
N *p;
int f;
while(q.empty() == false)
{
f = q.front();
q.pop();
if(f == 1)
{
cout<<"YES"<<endl;
return ;
}
//链表的遍历
for(p = head[f]->next;p != NULL;p = p->next)
{
if(mark[p->v] == false)
{
q.push(p->v);
mark[p->v] = true;
}
}
}
cout<<"NO"<<endl;
}
int main()
{
int n,m,i,u,v;
//生成头节点
for(i = 1;i < MAXN_Point; ++i)
{
head[i] = creat();
}
while(scanf("%d %d",&n,&m) != EOF)
{
//开始时所有的节点均无边。
for(i = 1;i <= n; ++i)
{
head[i]->next = NULL;
}
for(i = 0;i < m; ++i)
{
scanf("%d %d",&u,&v);
Link(u,v);
}
bfs(n);
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <stack>
#include <string>
#include <vector>
#pragma comment(linker, "/STACK:1024000000");
#define LL long long int
#define ULL unsigned long long int
#define _LL __int64
#define INF 0x3f3f3f3f
#define Mod 1000000009
using namespace std;
const int MAXN_Edge = 2000001;//边集大小
const int MAXN_Point = 1010;//点集大小
struct N
{
int u,v,next;//此处的next与链表中的next功能一样,都是记录下一个节点的位置。
}edge[MAXN_Edge];
int head[MAXN_Point];
//和链表的指针数组一样。只不过此处head[u]记录的为最后加入 edge 的且与u相连的边在 edge 中的位置,即下标。
int Top;//已经建立完成的边的数量
void Link(int u,int v)//将 v 链接到 u.
{
edge[Top].v = v;//更新数据域。
edge[Top].u = u;
edge[Top].next = head[u];//此时head[u]存储的上一条的下表,或者为-1.
head[u] = Top; //Top 即为刚加入 edge 的边的下标
}
bool mark[1010];
void bfs(int n)
{
queue<int> q;
memset(mark,false,sizeof(mark));
mark[n] = true;
q.push(n);
int f,p;
while(q.empty() == false)
{
f = q.front();
q.pop();
if(f == 1)
{
cout<<"YES"<<endl;
return ;
}
//遍历与f相连的所有边
for(p = head[f];p != -1; p = edge[p].next)
{
if(mark[edge[p].v] == false)
{
q.push(edge[p].v);
mark[edge[p].v] = true;
}
}
}
cout<<"NO"<<endl;
return ;
}
int main()
{
int i,u,v,n,m;
while(scanf("%d %d",&n,&m) != EOF)
{
//置为-1,和链表中的next指针指向NULL的意义相同。
memset(head,-1,sizeof(head));
Top = 0;//开始时建立完成的边的集合为空
for(i = 0;i < m; ++i)
{
scanf("%d %d",&u,&v);
Link(u,v);
}
bfs(n);
}
return 0;
}