Import java.util.ArrayList;
Import Java.util.HashSet;
Import java.util.List;
Import Java.util.Set;
/** No. 05 Lecture-Breadth First traversal _ transform to recursive method *------------------------------------* The recursive similarity of depth first traversal is obvious. * Breadth-first traversal can be recursive solution. Try to transform the solution of the course into recursive mode */public class Mywidthtravel {@SuppressWarnings ({"Rawtypes", "Unchecked"}) public static void Mai N (string[] args) {int[][] G = {0, 1, 1, 0, 0, 0, 0}, {1, 0, 0, 1, 0, 0, 1}, {1, 0, 0, 0, 0, 1, 1}
, {0, 1, 0, 0, 1, 0, 0}, {0, 0, 0, 1, 0, 1, 1}, {0, 0, 1, 0, 1, 0, 0}, {0, 1, 1, 0, 1, 0, 0}}; Set tag = new HashSet (); Save the already traversed node List layer = new ArrayList (); Waiting to traverse layer.add (0); The initial state, starting from number No. 0 to traverse Widthtravel (g, tag, layer); Call breadth-First traversal method}/** * Breadth-FIRST TRAVERSAL * * */@SuppressWarnings ({"Rawtypes", "Unchecked"}) public final static void width Travel (int[][] g, Set tag, List lst) {///3 parameters, adjacency table matrix, tag, to be traversed lst int node = (Integer) lst.get (0); Get the number No. 0 element System.out. println (node); Immediately output this element Tag.add (node); Add to the Mark Lst.remove (0); At the same time, remove the element from the LST//process all the children of this node immediately following for (int i = 0; i < g[node].length; i++) {//node row all elements to find if (g[node ][i] = = 1//Indicates that there is a connector between two nodes && tag.contains (i) = = false//exclude already traversed nodes, in the tag to determine whether to include this node &A
mp;& Lst.indexof (i) < 0) {//different nodes may have the same child, to determine if I node is already in LST, <0 that =-1, can not find. Lst.add (i); Join LST waiting for traversal} if (Lst.isempty () = False) {//If LST is not NULL, recursive widthtravel (g, tag, LST);
Recursive Self}}}