无向图的遍历
图
//用map和list存储图数据
Map<Character, List> map = new HashMap<>();
map.put('A', Arrays.asList('B', 'C'));
map.put('B', Arrays.asList('A', 'C', 'D'));
map.put('C', Arrays.asList('A', 'B', 'D', 'E'));
map.put('D', Arrays.asList('B', 'C', 'E', 'F'));
map.put('E', Arrays.asList('C', 'D'));
map.put('F', Arrays.asList('D'));
广度优先遍历
利用队列进行遍历
//
public static void BFS (Map<Character, List> map, char node) {
Set<Character> set = new HashSet<>();
Queue<Character> queue = new LinkedList<>();
queue.offer(node);
set.add(node);
while ( !queue.isEmpty()) {
char ch = ((LinkedList<Character>) queue).pop();
System.out.println(ch);
List<Character> list = map.get(ch);
for (Character c:list) {
if (!set.contains(c)) {
queue.offer(c);
set.add(c);
}
}
}
}
深度优先遍历
利用栈进行遍历
//
public static void DFS (Map<Character, List> map, char node) {
Set<Character> set = new HashSet<>();
Stack<Character> stack = new Stack<>();
stack.push(node);
set.add(node);
while ( !stack.isEmpty()) {
char ch = stack.pop();
System.out.println(ch);
List<Character> list = map.get(ch);
for (Character c:list) {
if (!set.contains(c)) {
stack.push(c);
set.add(c);
}
}
}
}