1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import java.util.*; class BFS { private static void bfs(Map<Character, Character []> graph, Character node, Set visited){ //https://www.runoob.com/java/data-queue.html Queue<Character> queue = new LinkedList<Character>(); queue.offer(node); visited.add(node); while(!queue.isEmpty()){ node = queue.poll(); System.out.println(node); for(Character neighbor:graph.get(node)){ if(!visited.contains(neighbor)){ queue.offer(neighbor); visited.add(neighbor); } } } } private static void stackBfs(Map<Character, Character []> graph, Character node, Set visited){ Deque<Character> stack = new LinkedList<>(); stack.push(node); visited.add(node); while(!stack.isEmpty()){ node = stack.pollLast(); System.out.println(node); for(Character neighbor:graph.get(node)){ if(!visited.contains(neighbor)){ stack.push(neighbor); visited.add(neighbor); } } } } private static void printMap(Map<Character, Character []> graph){ for (Map.Entry<Character, Character []> entry : graph.entrySet()){ System.out.println(entry.getKey() + ":" + Arrays.toString(entry.getValue())); } } public static void main(String[] args) { /* graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } */ Map<Character, Character []> graph = new HashMap<Character, Character []>(); graph.put('A', new Character [] {'B','C'}); graph.put('B', new Character [] {'D', 'E'}); graph.put('C', new Character [] {'F'}); graph.put('D', new Character [] {}); graph.put('E', new Character [] {'F'}); graph.put('F', new Character [] {}); printMap(graph); System.out.println("Queue BFS: "); Set visited=new HashSet(); bfs(graph, 'A', visited);
System.out.println("Stack BFS: "); visited=new HashSet(); stackBfs(graph, 'A', visited); } } > java -cp /tmp/fqlpjpJwBO BFS A:[B, C] B:[D, E] C:[F] D:[] E:[F] F:[] Queue BFS: A B C D E F Stack BFS: A B C D E F
|