【算法】图的广度优先搜索和深度优先搜索
我们构建一张如下的图:
直接上代码:
package main; import java.util.ArrayList; public class Node { private String name = ""; public ArrayList<Node> neighbor = new ArrayList<>(); public boolean flag = false; public Node(String name){ this.name = name; } public void addNeighbor(Node... nodes){ if(nodes != null){ for(Node temp:nodes){ neighbor.add(temp); } } } public String getName(){ return name; } }
1 package main; 2 3 import java.util.ArrayList; 4 import java.util.LinkedList; 5 import java.util.Queue; 6 import java.util.Stack; 7 import java.util.concurrent.ExecutorService; 8 import java.util.concurrent.Executors; 9 import java.util.concurrent.locks.Condition; 10 import java.util.concurrent.locks.Lock; 11 import java.util.concurrent.locks.ReentrantLock; 12 13 public class Main { 14 public static void main(String[] args){ 15 Node a = new Node("A"); 16 Node b = new Node("B"); 17 Node c = new Node("C"); 18 Node d = new Node("D"); 19 Node e = new Node("E"); 20 Node f = new Node("F"); 21 Node g = new Node("G"); 22 Node h = new Node("H"); 23 Node i = new Node("I"); 24 25 a.addNeighbor(b,f); 26 b.addNeighbor(a,g,i,c); 27 c.addNeighbor(b,i,d); 28 d.addNeighbor(c,i,g,h,e); 29 e.addNeighbor(d,h,f); 30 f.addNeighbor(a,g,e); 31 h.addNeighbor(g,d,e); 32 i.addNeighbor(b,c,d); 33 34 //深度优先 35 Stack<Node> stack = new Stack<>(); 36 stack.push(a); 37 a.flag = true; 38 while(!stack.isEmpty()){ 39 Node curNode = stack.pop(); 40 System.out.print(curNode.getName()); 41 for(Node temp:curNode.neighbor){ 42 if(temp.flag == false){ 43 stack.push(temp); 44 temp.flag = true; 45 } 46 } 47 } 48 System.out.println("\n"); 49 50 a.flag = false; 51 b.flag = false; 52 c.flag = false; 53 d.flag = false; 54 g.flag = false; 55 e.flag = false; 56 f.flag = false; 57 h.flag = false; 58 i.flag = false; 59 60 //广度优先 61 Queue<Node> queue = new LinkedList<>(); 62 queue.offer(a); 63 a.flag = true; 64 while(!queue.isEmpty()){ 65 Node curNode = queue.poll(); 66 System.out.print(curNode.getName()); 67 for(Node temp:curNode.neighbor){ 68 if(temp.flag == false){ 69 queue.offer(temp); 70 temp.flag = true; 71 } 72 } 73 } 74 75 System.out.print("\n"); 76 } 77 78 }
输出结果分别为:
AFEHDICGB
ABFGICEDH