Implementation of depth-first traversal of images c/c ++ DFS, deep dfs
# Include <iostream>
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
Using namespace std;
# Deprecision MAX 100
# Define LENGTH (a) (sizeof (a)/sizeof (a [0])
Int visited [MAX];
Typedef struct _ graph {
Char vexs [MAX];
Int vexnum;
Int edgnum;
Int matrix [MAX] [MAX];
} Graph, * PGgraph;
Static int get_position (Graph g, char ch ){
For (int I = 0; I <g. vexnum; I ++ ){
If (ch = g. vexs [I])
Return I;
}
Return-1;
}
Static char read_char (){
Char ch;
While (! (Ch)> = 'A') & (ch) <= 'Z') | (ch)> = 'A ') & (ch) <= 'Z '))))
Ch = getchar ();
Return ch;
}
Graph creat_graph (){
Char c1, c2;
Int v, e;
Int p1, p2;
Graph pG;
Cout <"input number of vex> ";
Cin> v;
Cout <"input number of edge> ";
Cin> e;
// Memset (pG, 0, sizeof (Graph ));
PG. vexnum = v;
PG. edgnum = e;
// Initialize vexs
For (int I = 0; I <pG. vexnum; I ++ ){
// PG. vexs [I] = read_char ();
Cin> pG. vexs [I];
}
// Initialize edges
For (int I = 0; I <pG. edgnum; I ++ ){
// C1 = read_char ();
// C2 = read_char ();
Cin> c1> c2;
Cout <c1 <c2 <endl;
P1 = get_position (pG, c1 );
P2 = get_position (pG, c2 );
PG. matrix [p1] [p2] = 1;
PG. matrix [p2] [p1] = 1;
}
Return pG;
}
Static int next_vertex (Graph g, int v, int w ){
If (v <0 | v> g. vexnum-1 | w <0 | w> (g. vexnum-1) return-1;
For (int I = w + 1; I <g. vexnum; I ++ ){
If (g. matrix [v] [I] = 1) return I;
}
Return-1;
}
Static int first_vertex (Graph g, int v ){
If (v <0 | v> g. vexnum-1) return-1;
For (int I = 0; I <g. vexnum; I ++ ){
If (g. matrix [v] [I] = 1) return I;
}
Return-1;
}
Void DFS (Graph g, int I ){
If (visited [I] = 0 ){
Visited [I] = 1;
Cout <g. vexs [I] <"";
}
Int w = first_vertex (g, I );
For (; w> = 0; w = next_vertex (g, I, w )){
If (! Visited [w]) DFS (g, w );
}
}
Int main (int argc, const char * argv []) {
For (int I = 0; I <MAX; I ++ ){
Visited [I] = 0;
}
Graph g;
G = creat_graph ();
For (int I = 0; I <g. vexnum; I ++ ){
If (! Visited [I]) DFS (g, I );
}
Return 0;
}