Package COM. WZS; import Java. util. using list; import Java. util. queue; // graph traversal public class graph {// adjacent matrix storage graph // -- a B c d e f g h I // a 0 1 0 0 0 0 1 1 0/ /B 1 0 1 0 0 0 1 0 1/C 0 1 0 0 0 0 0 1/D 0 0 1 0 1 0 1 1 1/E 0 0 0 1 0 1 0 1 0 // F 1 0 0 1 0 1 0 0 0 // G 0 1 0 1 0 1 0 1 0 1 0 // H 0 0 0 1 1 0 1 0 0 // I 0 1 1 1 0 0 0 0 0 // Number of vertices private int number = 9; // record whether vertex is accessed private Boolean [] flag; // vertex private String [] vertexs = {"A", "B", "C", "D", "E", "F", "g", "H ", "I"}; // edge private int [] [] edges = {0, 1, 0, 0, 0, 1, 1, 0}, {1, 0, 1, 0, 0, 0, 1, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 1, 0, 1, 1, 1}, {0, 0, 0, 1, 0, 1, 0, 1, 0}, {1, 0, 0, 0, 1, 0, 1, 0, 0}, {0, 1, 0, 1, 0, 1, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 1, 0, 0}, {0, 1, 1, 1, 0, 0, 0, 0, 0 }}; // deep graph traversal (recursion) void dfstr Averse () {flag = new Boolean [number]; for (INT I = 0; I <number; I ++) {If (flag [I] = false) {// The current vertex is not accessed by DFS (I) ;}}// the depth-first recursive algorithm void DFS (int I) {flag [I] = true; // The vertex I is accessed by system. out. print (vertexs [I] + ""); For (Int J = 0; j <number; j ++) {If (flag [J] = false & edges [I] [J] = 1) {DFS (j );}}} // void bfstraverse () {flag = new Boolean [number]; queue <integer> queue = new vertex list <integer> (); For (INT I = 0; I <number; I ++) {If (flag [I] = false) {flag [I] = true; system. out. print (vertexs [I] + ""); queue. add (I); While (! Queue. isempty () {Int J = queue. poll (); For (int K = 0; k <number; k ++) {If (edges [J] [k] = 1 & flag [k] = false) {flag [k] = true; system. out. print (vertexs [k] + ""); queue. add (k) ;}}}}// test public static void main (string [] ARGs) {graph = New Graph (); system. out. println ("Deep graph traversal (recursion):"); graph. dfstraverse (); system. out. println ("\ n -------------"); system. out. println ("Graph breadth traversal operation:"); graph. bfstraverse ();}}
Output result:
Depth traversal (recursion): a B c d e f g h I ------------- breadth traversal of the graph: a B f g c I e d H