BFS(广度优先搜索)
邻接矩阵代码
void bfs(int k) {
int head = 0, tail = 1;
q[tail] = k;
while(head++ < tail)
for(int i = 1; i <= n; i++)
if(a[q[head]][i] && !vis[i]) {
vis[i] = 1;
q[++tail] = i;
}
}
邻接表代码
void bfs(int k) {
int head = 0, tail = 1;
q[tail] = k;
while(head++ < tail)
for(int i = lin[ q[head] ]; i ; i = e[i].next)
if(!vis[ e[i].y ]) {
vis[ e[i].y ] = 1;
q[++tail] = e[i].y;
}
}
DFS(深度优先搜索)
邻接矩阵代码
void dfs(int k) {
for(int i = 1; i <= n; i++)
if(a[k][i] && !vis[i]) vis[i] = 1, dfs(i);
}
邻接表代码
void dfs(int k) {
for(int i = lin[k]; i ; i = e[i].next)
if(!vis[e[i].y]) vis[e[i].y] = 1,dfs(e[i].y);
}