Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Graph Depth First Search
//clang 3.8.0 #include <stdlib.h> #include <stdio.h> struct node{ int vertex; struct node *next; }; struct Graph{ int numVertices; int *visited; struct node **adjLists; }; typedef struct node Node; typedef struct Graph Graph; Node* createNode(int); Graph* createGraph(int); void DFS(Graph*,int); void addEdge(Graph*,int,int); void printGraph(Graph*); int main(void) { Graph *g=createGraph(4); addEdge(g,0,1); addEdge(g,0,2); addEdge(g,0,3); addEdge(g,2,1); printGraph(g); DFS(g,3); return 0; } Node* createNode(int vertex){ Node *newNode=malloc(sizeof(Node)); newNode->vertex=vertex; newNode->next=NULL; return newNode; } Graph* createGraph(int vertices){ Graph *g=malloc(sizeof(Graph)); g->visited=malloc(vertices*sizeof(int)); g->adjLists=malloc(vertices*sizeof(Node)); g->numVertices=vertices; for(int i=0;i<vertices;i++ ){ g->adjLists[i]=NULL; g->visited[i]=0; } return g; } void DFS(Graph* g,int vertex){ Node *adjList=g->adjLists[vertex]; Node *temp=adjList; g->visited[vertex]=1; printf("Visited %d\n",vertex); while(temp!=NULL){ int connectedVertex=temp->vertex; if(g->visited[connectedVertex]==0) DFS(g,connectedVertex); temp=temp->next; } } void addEdge(Graph* g,int src,int des){ Node *temp=createNode(des); temp->next=g->adjLists[src]; g->adjLists[src]=temp; temp=createNode(src); temp->next=g->adjLists[des]; g->adjLists[des]=temp; } void printGraph(Graph* g){ for(int i=0;i<g->numVertices;i++ ){ Node *temp=g->adjLists[i]; printf("Adjacency list of vertex %d\n",i); while(temp){ printf("%d->",temp->vertex); temp=temp->next; } printf("\n"); } }
run
|
edit
|
history
|
help
1
Vectores: Burbuja ordenación
fun kce
Linear Classifier in C
Pointer_Indirectare_N
VKI_Mihalyk_3_3
0002
Vzdalenost makro inline
vyměna proměnych pomoci parametru
ejemplos bucles basicos
Día de la semana