1.深度优先搜索(DFS)
/**
* 深度优先搜索(DFS, Depth First Search)
* DFS使用栈(stack)来实施算法过程
* stack具有后进先出LIFO(Last Input First Output)的特性,DFS的操作步骤如下:
*/
// 1、把起始点放入stack;
// 2、重复下述3步骤,直到stack为空为止:
// 从stack中访问栈顶的点;
// 找出与此点邻接的且尚未遍历的点,进行标记,然后全部放入stack中;
// 如果此点没有尚未遍历的邻接点,则将此点从stack中弹出。
private Stack<String> stack = new Stack<String>();
public void DFSSearch(String startPoint) {
stack.push(startPoint);
status.put(startPoint, true);
dfsLoop();
}
private void dfsLoop() {
if(stack.empty()){
return;
}
//查看栈顶元素,但并不出栈
String stackTopPoint = stack.peek();
// 2) 找出与此点邻接的且尚未遍历的点,进行标记,然后全部放入queue中。
List<String> neighborPoints = graph.get(stackTopPoint);
for (String point : neighborPoints) {
if (!status.getOrDefault(point, false)) { //未被遍历
stack.push(point);
status.put(point, true);
dfsLoop();
}
}
String popPoint = stack.pop();
System.out.println(popPoint);
}