图的宽度优先算法
package WebCrawler; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; public class Graph { private HashMap<String, ArrayList<String>> adj; // 邻接表 private ArrayList<String> visited; public Graph() { adj = new HashMap<String, ArrayList<String>>(); visited = new ArrayList<String>(); } public void addVertex(String v) { adj.put(v, new ArrayList<String>()); } public void addEdge(String fromVertex, String toVertex) { adj.get(fromVertex).add(toVertex); adj.get(toVertex).add(fromVertex); } public void printGraph() { for (String key : adj.keySet()) { System.out.println(key + ": " + adj.get(key)); } } public void broadFirstSearch(String startVertex) { try { Queue<String> q = new LinkedList<String>(); q.add(startVertex); //入列 visited.add(startVertex); while (!q.isEmpty()) { String head = q.poll(); //出列 //System.out.println(head); ArrayList<String> toVisit = adj.get(head); for (String s : toVisit) { if (!visited.contains(s)) { visited.add(s); q.add(s); } } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Graph g = new Graph(); g.addVertex("A"); g.addVertex("B"); g.addVertex("C"); g.addEdge("A", "B"); g.addEdge("A", "C"); g.printGraph(); g.broadFirstSearch("A"); } }