第一步,构造一个图,图的结构如下
这个图构造方式有二种,一种二维数组,一种Map + 链表,因为图比较稀疏,使用Map加链表来构建,代码如下所示
private static Map<Character,List<Character>> buildGraph(){ Map<Character, List<Character>> graph = new HashMap<>(); List<Character> aList = new LinkedList<>(Arrays.asList('B','C')); List<Character> bList = new LinkedList<>(Arrays.asList('A','C','D')); List<Character> cList = new LinkedList<>(Arrays.asList('A','B','D','E')); List<Character> dList = new LinkedList<>(Arrays.asList('B','F','E','C')); List<Character> eList = new LinkedList<>(Arrays.asList('C','D')); List<Character> fList = new LinkedList<>(Arrays.asList('D')); graph.put('A',aList); graph.put('B',bList); graph.put('C',cList); graph.put('D',dList); graph.put('E',eList); graph.put('F',fList); return graph; }
Map的key表示节点,Value是邻接节点组成的链表。
广度优先搜索 bfs:思想就是先访问当前节点,然后访问当前节点的邻接节点,依次类推。使用队列的先进先出特性,可以按层遍历。
深度优先搜索 bfs:思想就是先访问当前节点,然后一直访问走,直到路不通,然后往回走。
public static void main(String[] args) { Map<Character, List<Character>> graph = buildGraph(); dfs(graph, 'C'); bfs(graph, 'D'); } private static Map<Character,List<Character>> buildGraph(){ Map<Character, List<Character>> graph = new HashMap<>(); List<Character> aList = new LinkedList<>(Arrays.asList('B','C')); List<Character> bList = new LinkedList<>(Arrays.asList('A','C','D')); List<Character> cList = new LinkedList<>(Arrays.asList('A','B','D','E')); List<Character> dList = new LinkedList<>(Arrays.asList('B','F','E','C')); List<Character> eList = new LinkedList<>(Arrays.asList('C','D')); List<Character> fList = new LinkedList<>(Arrays.asList('D')); graph.put('A',aList); graph.put('B',bList); graph.put('C',cList); graph.put('D',dList); graph.put('E',eList); graph.put('F',fList); return graph; } /** * 深度优先搜索 * @param graph 要遍历的图 * @param s 起始点 */ public static void dfs(Map<Character,List<Character>> graph, Character s){ //走过的节点 Set<Character> visited = new HashSet<>(); Stack<Character> stack = new Stack<>(); stack.push(s); while(!stack.empty()){ Character accessC = stack.pop(); if(!visited.contains(accessC)){ System.out.print("->"+accessC); visited.add(accessC); } graph.get(accessC).forEach(c ->{ if(!visited.contains(c)){ stack.push(c); } }); } } public static void bfs(Map<Character,List<Character>> graph, Character s){ //走过的节点 Set<Character> visited = new HashSet<>(); Queue<Character> queue = new LinkedList<>(); queue.offer(s); while (!queue.isEmpty()){ Character accessC = queue.poll(); if(!visited.contains(accessC)){ System.out.print("->"+accessC); visited.add(accessC); } graph.get(accessC).forEach(c ->{ if(!visited.contains(c)){ queue.offer(c); } }); } }