Simple code for handwriting of the adjacent table and the adjacent matrix DFS BFS
This is the DFS through the adjacent matrix.
# Include
# Include
# Include
# Define Max_ver_num 20 using namespace std; bool visit [Max_ver_num]; // The purpose of this array is to mark structHGraph {string vexs [Max_ver_num]; // put the name of the array of each vertex int arcs [Max_ver_num] [Max_ver_num]; //; adjacent matrix int vexnum; // Number of vertices int arcnum; // Number of edges, the edge here has no weight}; int Locate (HGraph G, string x) {// determine the vertex position int k = 0; while (G. vexs [k]! = X) {k ++;} return k;} void Create (HGraph & G) {// Create a graph. The graph here refers to constructing an undirected graph, build int I = 0, j, k; cout <"Number of vertices and edges of the input graph:"; cin> G. vexnum> G. arcnum; cout <"enter the names of each vertex in sequence:"; while (I
> G. vexs [I ++] ;}for (I = 0; I <G. vexnum; I ++) {for (j = 0; j <G. vexnum; j ++) {G. arcs [I] [j] = 0 ;}} for (k = 0; k
> V1> v2; I = Locate (G, v1); j = Locate (G, v2); while (I <0 | j <0) {cout <"incorrect input. Please try again:"; cin> v1> v2; I = Locate (G, v1); j = Locate (G, v2);} G. arcs [I] [j] = 1; G. arcs [j] [I] = G. arcs [I] [j]; // because it is an undirected graph, it is mutually ~;} Cout <"done" <
Through the BFS through the adjacent table, I think it is easy to write, although it is very difficult to write
# Include
# Include
# Include
# Include
Using namespace std; # define Max 20 bool visit [20]; // same as in the previous undirected graph, it is later used to determine whether the int Vex_Num has been accessed; // This is displayed on the Internet. It is mainly used to determine whether each vertex has accessed struct ArcNode {int adjvex; // ArcNode * nextarc, the vertex position indicated by the arc; // point to next-> arc}; typedef struct VNode {string data; // vertex ArcNode * firarc; // The first vertex of the fox} AdjList [Max]; struct HGraph {AdjList vertices; // header node array int vexnum; // Number of vertices int arcnum; // Number of edges}; int Locate (HGraph G, string x) {// locate the vertex position Int v; for (v = 0; G. vertices [v]. data! = X; v ++) {// donothing}; return v;} void Create (HGraph & G) {string v1, v2; int I, j, k; cout <"Enter the number of vertices and number of edges:"; cin> G. vexnum> G. arcnum; cout <"Enter the vertex name:"; for (I = 0; I
> G. vertices [I]. data; G. vertices [I]. firarc = NULL;} for (k = 0; k
> V1> v2; I = Locate (G, v1); j = Locate (G, v2); while (I <0 | j <0) {cout <"error. Enter"; cin> v1> v2; I = Locate (G, v1); j = Locate (G, v2 );} arcNode * p = new ArcNode; p-> adjvex = j; p-> nextarc = G. vertices [I]. firarc; G. vertices [I]. firarc = p ;}} void BFS_Tra (HGraph G) {Vex_Num = 0; int I, k, w; queue
Q; ArcNode * p; for (I = 0; I
Nextarc) {w = p-> adjvex; if (! Visit [w]) {visit [w] = true; cout <