Two methods of adjacency matrix and adjacency table to implement the BFS and DFS of the non-direction graph

Source: Internet
Author: User

Breadth-First search (Breadth-first-search) and depth-first search (Deep-first-search) are two of the most commonly used methods in search strategies, especially for graph searches.


The idea of BFS:
Starting at one vertex of a graph, V0 first accesses and V0 adjacent and inaccessible vertices V1, V2 、...... Vn, then visit with V1, V2 ... A vertex that is adjacent to the VN and is not accessed. So continue, find the vertex you are looking for or traverse the entire graph. We use queues to store the nodes that have been accessed.


The idea of Dfs:

The strategy followed by depth-first search is to search in the diagram as "deep" as possible, and for one vertex v in the graph, if it has adjacent vertices and is not accessed, the vertex is accessed. If it is not found, it returns to the previous vertex. This process continues until all vertices are accessed. DFS can search for all paths from one vertex to another. Due to the return operation, we are using a recursive method.


adjacency table:

Adjacency table is a chain storage structure of graphs. In the adjacency table, a single linked list is created for each vertex vi in the graph, and the vertices adjacent to the Fish VI are placed in the linked list.


Adjacency Matrix:

An adjacency matrix is a matrix that represents the neighboring relationships between vertices. Set g (V,e) is an n-vertex-free graph, then it corresponds to an n-order matrix. If the square is set to a, then for A[I][J] There are two kinds of values, when a[i][j]=1, the vertex i and Vertex j is connected, when a[i][j]=0, the vertex i and Vertex j is not connected.


Adjacency Matrix-based Dfs:

<span style= "FONT-SIZE:14PX;" >//based on adjacency matrix DFS, Time complexity O (n^2) #include <stdio.h> #include <string.h>const int gnumber = 8;//number of storage nodes int g[ gnumber][gnumber];//storage adjacency matrix int color[gnumber];//storage node state void dfs_visit (int g[][gnumber], int i, int n) {int j;color[i] = 1; for (j=0; j< N; j + +) {if (G[i][j] &&!color[j]) {printf ("v%d", j+1); Color[j] = 1;dfs_visit (G, J, n);}} void DFS (int g[][gnumber], int n) {int i;memset (color, 0, sizeof (color)), for (i=0; i<n; i++) {//traversal of each node if (!color[i]) {// Determine whether to access printf ("v%d", i+1);D fs_visit (g,i,n);p rintf ("\ n");}} int main () {FILE *fr;int i,j;fr = fopen ("Test case. txt", "R"), if (!FR) {printf ("fopen failed\n"); return-1;} while (Fscanf (FR, "%d%d", &i, &j)! = EOF) {G[i-1][j-1] = 1; G[J-1][I-1] = 1;} DFS (G,gnumber); GetChar (); return 0;} </span>



BFS based on adjacency matrix:

<span style= "FONT-SIZE:14PX;" >//based on adjacency matrix of BFS, Time complexity O (n^2) #include <stdio.h> #include <string.h>const int gnumber = 8;//storage node Number int g[ gnumber][gnumber];//storage adjacency Matrix int color[gnumber];//prevent loopback, record node state struct queue{//use array to simulate queue int Queue[gnumber];int Start;int End;} Myqueue;void BFS (int g[][gnumber], int n) {int J; myqueue.queue[myqueue.end++] = 0;color[0] = 1;while (myqueue.end! = Myqueue.start) {for (j=0; j<n; J + +) {if (G[ MYQUEUE.START][J] &&!color[j]) {color[j] = 1; myqueue.queue[myqueue.end++] = j;}} printf ("v%d", Myqueue.queue[myqueue.start++]+1);}} int main (int argc, char **argv) {FILE *fr;int i,j;fr = fopen ("Test case. txt", "R"), if (!FR) {printf ("fopen failed\n"); return-1;} printf ("%d%d\n", myqueue.start,myqueue.end); while (Fscanf (FR, "%d%d", &i, &j)! = EOF) {G[i-1][j-1] = 1; G[J-1][I-1] = 1;} memset (&myqueue, 0, sizeof (myqueue)), memset (color, 0, sizeof (color)); BFS (G,gnumber); GetChar (); return 0;} </span> 


BFS and DFS based on adjacency table:

<span style= "FONT-SIZE:14PX;" > #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 8//MAX vertex number typedef struct node  {//edge node int adjvex;  The vertex position that the edge points to//int weight struct node* next;        Pointer to next edge}arcnode;//Edge table node typedef struct vnode{int vertex; arcnode* Firstarc;        Pointer to the first attachment to the vertex}vnode;//Vertex table node typedef vnode ADJLIST[MAX+1];//ADJ_LIST is the adjacency table type typedef struct {int n, m;//the number of vertices and sides of the graph    Adjlist adjlist;//adjacency table}algraph;void create_algraph (algraph* g)//Create an adjacency table of the non-map {arcnode* newnode; int I, J, k;printf ("Please input node number and edge number:"), scanf ("%d%d", &g->n, &g->m);p rintf ("Node Nu Mber =%d, edges =%d\n ", g->n, G->m); for (i = 1; I <= g->n; i++) {G->adjlist[i].vertex = I;g->adjlist[i]. Firstarc = NULL;} printf ("Please input new edge: \ n");//Use the adjacent two vertices to represent the edge for (k = 1; k <= g->m; k++) {scanf ("%d%d", &i, &j);//printf ( "\ n"); newnode = (arcnode*) malloc (sizeof (Arcnode)); Newnode->adJvex = J;//newnode->weight = 0;newnode->next = G->adjlist[i].firstarc;g->adjlist[i].firstarc = NewNode; NewNode = (arcnode*) malloc (sizeof (Arcnode)); Newnode->adjvex = I;//newnode->weight = 0;newnode->next = g-> Adjlist[j].firstarc;g->adjlist[j].firstarc = NewNode;}} void Pr_algraph (algraph* g)//Output adjacency table {arcnode* Node;int i;for (i = 1; i<= g->n; i++) {node = G->adjlist[i].firstarc;p rintf ("g->adjlist[%d] =%d:", I, G->adjlist[i].vertex); while (node! = NULL) {printf ("%d \ T", Node->adjvex); node = Node->next;} printf ("\ n");}} int visted[max+1];//record node state void DFS (Algraph *g,int v) {Visted[v] = 1;//Access initial point Arcnode *p = G->adjlist[v].firstarc;while ( P!=null) {if (visted[p->adjvex]==0) {////If not accessed, recursively calls DFS access printf ("%d", P->adjvex);D FS (G,p->adjvex);} P = p->next;//continues to the next edge}//printf ("\ n");} void BFS (Algraph *g,int v) {//for (int i=0;i<g->n;i++) visted[i] = 0;int Queue[max],front,rear;front = Rear = 0;rear = (rear+1)%max;queue[rear] = v; v vertex enqueued int u; ArcNode *p;while (/*rear!=0*/front!=rear)//When the queue is full {front = (front+1)%max;u = Queue[front];p = g->adjlist[u].firstarc; while (P!=null)//First Access all nodes of U {if (visted[p->adjvex]==0) {Visted[p->adjvex] = 1;//Access P->adjvex node, marked for access rear = ( rear+1)%max;printf ("%d", P->adjvex); Queue[rear] = P->adjvex;//p->adjvex node enqueued}p = P->next;}} printf ("\ n");} int main (int argc, char** argv) {algraph* g;//defines an none graph G = (algraph*) malloc (sizeof (algraph));p rintf ("Begin Create Algraph\ N "), Create_algraph (g);p rintf (" Finish Create algraph\n ");p rintf (" The Algraph is:\n ");p r_algraph (g); memset (visted,0, sizeof (visted)); visted[1]=1;printf ("BFS is:\n");p rintf ("1"); BFS (g,1), memset (visted,0,sizeof (visted));p rintf ("DFS is:\n");p rintf ("1");D FS (g,1);p rintf ("\ n"); return 0;} </span>
The adjacency matrix and adjacency table are all methods to implement BFS and DFS, the adjacency matrix time complexity is O (n^2), the time complexity of adjacency table is O (n+e), so the adjacency matrix is suitable for dense graphs, and adjacency table is suitable for sparse graphs.


Two methods of adjacency matrix and adjacency table to implement the BFS and DFS of the non-direction graph

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.