"Graph" of data structures and algorithms

Source: Internet
Author: User

In fact, all data structures are "graphs". A graph is actually a collection of vertices and edges. If the edge has a directivity is called a directed graph, otherwise it is a graph, edge can also have the right value. A graph with a path connection between any two points is called a connected graph, and the number of edges connected by vertices is called the degree of the vertex.

Connected graphs without loops are called trees, and non-connected graphs without loops are forests.

1, the representation of the figure

(1) adjacency matrix

Use | v|*| A two-dimensional array of v| to represent: Graph[v][v]. GRAPH[I][J] represents the relationship between vertex I and Vertex J, in an unauthorized graph, graph[i][j]=1 represents an edge between I,j and =0 represents infinity. In an graph[i][j diagram, this is a heap matrix; If a weighted graph is taken, then the weight of the edge of vertex I to the vertex J is represented by the Infinity Graph[i][j]=inf.

The adjacency matrix can be used to determine if there is an edge between two points in the O (1) time, but the cost is O (| V|2) space. In the non-direction graph, because it is a symmetric matrix, at least the general space is wasted; when the edges of a graph are small, space utilization is lower.

(2) adjacency table

Each vertex has an adjacency table containing all the vertices that are adjacent to the vertex. The adjacency table only needs to occupy O (| v|+| e|) Space, greatly improving the utilization of space. The adjacency table also has two representations, which are represented by the linked list, or the adjacency list, or an adjacency array, represented by an array. The spatial complexity of contiguous or contiguous arrays is asymptotically equal, but in many algorithms of graphs, adjacency arrays take less time than adjacency matrices.

Here is the representation of the adjacency table:

vector<int> G[max_v]; // Max_v as vertex number

Where G[i] represents the adjacency table of vertex i.

Determine if the Edge (I,J) exists in Figure G:

bool existsedge (int i,int  j) {    vector<int>:: iterator it;     for (It=g[i].begin (); It!=g[i].end (); it++)        if(j = = *it            ) return true ;     return false ;}

Insert an edge into G (I,J):

void Insertedge (int i,int  j) {    if(Existsedge (i,j)         ) return  ;    G[i].push_back (j);    G[j].push_back (i);}

Remove an edge from G (I,J):

void Eraseedge (int i,int  j) {    for (It=g[i].begin (); It!=g[i].end (); it++)        if(j = = *it)            g[i].erase (it)    ;  for (It=g[j].begin (); It!=g[j].end (); it++)         if (i = = *it)            G[j].erase (it);}

The degree of vertex I:

int degree (int  i) {    return  g[i].size ();}

2, the graph of the traversal

Where the flag array is used to record the vertices that have been searched. Here the G[max_v] is a graph of no direction, through which all edges are printed.

(1) Depth-first traversal (DFS)

Starting with a vertex V, select a vertex that is adjacent to V and not reached u, if u exists, then start new Dfs from U, otherwise, u exists, end search returns.

 void  dfs (int   V) { static  int  flag[max_v] = {0  };    FLAG[V]  = 1  ;  for  (int  i= 0 ; I<g[v].size (); I++ if  (            0  == Flag[g[v][i]]) {DFS (g[v][i]); printf (   " ,v,g[v][i]); }    }}

(2) Breadth-first traversal (BFS)

In fact, the BFS is the same as the sequence traversal of the tree, starting from a vertex, access all its adjacent vertices, and put the visited adjacent vertices into the queue, each time after accessing all the adjacent vertices, the queue to remove a vertex, and then continue the previous operation until the number of elements in the queue is 0.

voidBFsintv) {Queue<int>que; BOOLFlag[max_v]; Fill (Flag,flag+max_v,false);    Que.push (v); FLAG[V]=true;  while(!Que.empty ()) {        intVI =Que.front ();        Que.pop (); Vector<int>it;  for(It=g[vi].begin (); It!=g[vi].end (); it++){            if(!flag[*it]) {printf ("%d <-->%d\n", vi,*it); Que.push (*it); flag[*it] =true; }        }    }}

Graph as the most advanced data structure, all applicable to the graph algorithm, can be applied to the tree, linear table. DFS and BFS are the most commonly used two algorithms in the graph, and many other graph algorithms include the minimum spanning tree, the shortest path algorithm, all using the idea of Dfs and BFS.

Code See: Https://github.com/whc2uestc/DataStructure-Algorithm/tree/master/graph

"Graph" of data structures and algorithms

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.