首先須要知道的是,圖的深度優先遍歷是一種相似於樹的前序遍歷方式,即選擇一個入口節點,沿着這個節點一直遍歷下去,直至全部節點都被訪問完畢;若是說,圖的深度優先遍歷相似於樹的前序遍歷的話,那麼圖的廣度優先遍歷就相似於樹的層序遍歷了,即一層一層的去遍歷節點,直至全部節點都被訪問完畢。java
很少說,直接上代碼,會對部分代碼添加說明。node
import java.util.*; public class Traverse{ public static void main(String[] args){ //接受輸入,好比int類型,節點Node存儲各個圖節點;Path存儲各個節點做爲開始的路徑 Traverse tr = new Traverse(); System.out.print("深度優先遍歷是:"); ArrayList<Node>visited = new ArrayList<>(); visited.add(a); tr.depthFirstSearch(a); System.out.print("廣度優先遍歷是:"); tr.wudthSearch(a); } public void depthFirstSearch(Node a,List<Node> visited){ for(int i=0;i<a.out.size();i++){ Node cur = a.out.get(i).end; //打印當前結點 System.out.println(cur.node); if(!visited.contains(cur)){ visited.add(cur); depthFirstSearch(cur,visited); } } } public void widthSearch(Node a){ Set<Node> visited = new HashSet<>(); Queue<Node> q = LinkedList<>(); q.offer(a); while(!q.isEmpty()){ Node cur = q.poll(); //檢查是否已訪問該節點,避免重複訪問 if(!visited.contains(cur)){ visited.add(cur); //打印當前結點 System.out.println(cur.node); } for(int i =0;i<a.out.size();i++){ q.offer(a.out.get(i).end); } } } } //節點 class Node{ int node; ArrayList<Path>out; public Node(int node){ //初始化 this.node = node ; out = new ArrayList<>() } } //路徑 class Path{ Node start; Node end; public Path(Node start,Node end){ this.start=start; this.end=end; } }