```c## 图
//深搜
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int visit[1000] = { 0 };
typedef struct enode*edge;
struct enode {
int v1, v2, weight;
};
typedef struct node*Node;
struct node {
int adjl;
int weight;
Node next;
};
typedef struct {
Node firstedge;
int data;
}adjlist[1000];
typedef struct gnode*lgraph;
struct gnode {
int ne, nv;
adjlist G;
};
lgraph creat(int nv) {
lgraph graph = (lgraph)malloc(sizeof(struct gnode));
graph->nv = nv;
graph->ne = 0;
for (int i = 0; i < nv; i++)
graph->G[i].firstedge = NULL;
return graph;
}
void insert(lgraph graph,edge e) {
Node newnode =(Node)malloc(sizeof(struct node));
newnode->adjl = e->v2;
newnode->weight = e->weight;
newnode->next = graph->G[e->v1].firstedge;
graph->G[e->v1].firstedge = newnode;
}
lgraph build() {
lgraph graph;
int nv, ne;
scanf_s("%d%d", &nv, &ne);
graph = creat(nv);
if (ne != 0) {
for (int i = 0; i < ne; i++) {
edge e = (edge)malloc(sizeof(struct enode));
scanf_s("%d%d%d", &e->v1, &e->v2, &e->weight);
insert(graph,e);
}
}
return graph;
}
void DFS(lgraph graph,int n) {
Node w;
visit[n] = 1;
printf("v%d ", n);
for (w = graph->G[n].firstedge; w; w = w->next) {
if (!visit[w->adjl]) {
visit[w->adjl] = 1;
DFS(graph, w->adjl);
}
}
}
int main() {
int n;
lgraph graph = build();
while (scanf_s("%d", &n) != EOF) {
memset(visit, 0, 1000);
DFS(graph,n);
}
}
//广搜
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int visit[1000] = { 0 };
typedef struct enode *edge;
struct enode {
int v1, v2, weight;
};
typedef struct node *Node;
struct node {
int adjl;
int weight;
Node next;
};
typedef struct {
int data;
Node firstedge;
}adjlist[1000];
typedef struct gnode *lgraph;
struct gnode {
int nv, ne;
adjlist G;
};
lgraph creat(int nv) {
lgraph graph = (lgraph)malloc(sizeof(struct gnode));
graph->nv = nv;
graph->ne = 0;
for (int i = 0; i < nv; i++)
graph->G[i].firstedge = NULL;
return graph;
}
void insert(lgraph graph, edge e) {
Node newnode = (Node)malloc(sizeof(struct node));
newnode->adjl = e->v2;
newnode->weight = e->weight;
newnode->next = graph->G[e->v1].firstedge;
graph->G[e->v1].firstedge = newnode;
}
void BFS(lgraph graph,int n) {
int i=0,j=0;
Node w;
int Q[1000];
Q[j++] = n;
visit[n] = 1;
printf("v%d ", n);
while (i != j) {
w = graph->G[Q[i++]].firstedge;
while (w) {
if (!visit[w->adjl]) {
visit[w->adjl] = 1;
Q[j++] = w->adjl;
printf("v%d ", w->adjl);
}
w = w->next;
}
}
}
lgraph build() {
int nv, ne;
scanf_s("%d%d",&nv,&ne);
lgraph graph = creat(nv);
if (ne != 0) {
for (int i = 0; i < ne; i++) {
edge e = (edge)malloc(sizeof(struct enode));
scanf_s("%d%d%d", &e->v1, &e->v2, &e->weight);
insert(graph, e);
}
}
return graph;
}
int main() {
int n;
lgraph graph;
graph = build();
while (scanf_s("%d", &n) != EOF && n != -1) {
memset(visit, 0, 10
BFS(graph, n);
}
}
## 图
07-24
07-24