广度优先搜索:bredth-first search BFS
图由节点和边组成。一个节点可能与众多节点相连,这些结点被称为邻居。
可以使用广度优先搜索查找最短路径
队列是一种先进先出(First in First Out,FIFO)的数据结构。队列只支持两种操作:入队和出队
栈是一种后进先出(Last In First Out,LIFO)的数据结构
广度优先搜索运行时间为O(点数+边数),这通常写作O(V+E),其中V为顶点(vertice)数,E为边数
Python实现图的广度优先
# 广度优先
def dfs():
# 构造图
graph = {}
graph["you"] = ["alice","bob","claire"]
graph["bob"] = ["anuj","peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom","jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
# 将图加入队列
from collections import deque
search_queue = deque()
search_queue += graph["you"]
# 记录已经检查过的元素
searched = []
while search_queue:
person = search_queue.popleft()
if person not in searched:
if person_is_seller(person):
print(person + " is a mongo seller!")
return True
else:
search_queue += graph[person]
searched.append(person)
return False
# 如果名字以m结尾则是芒果供应商
def person_is_seller(name):
return name[-1] == 'm'
java实现图的广度优先搜索
/**
* 图的广度优先搜索
*/
public class DFS {
/**
* 图
*/
private Map<String,String[]> graph;
/**
* 记录被访问的节点
*/
private Set<String> searched;
/**
* 使用队列存放被访问的节点
*/
private Queue<String> queue;
public DFS(Map<String,String[]> graph,String source){
this.graph = graph;
this.searched = new HashSet<>();
this.queue = new LinkedList<>();
//初始化图
addQueue(source);
}
public boolean dfs(){
while (!queue.isEmpty()){
String person = queue.poll();
if(!searched.contains(person)){
if(searchSeller(person)){
System.out.println(person+" is a mango seller!");
return true;
}else {
addQueue(person);
}
}
}
return false;
}
/**
* 寻找芒果销售商(名字以m结尾)
* @param name
* @return
*/
private boolean searchSeller(String name){
return name.endsWith("m");
}
/**
* 将相邻节点加入队列
* @param person
*/
private void addQueue(String person){
String[] array = graph.get(person);
if(array.length > 0){
for(int i = 0; i < array.length;i++){
queue.add(array[i]);
searched.add(person);
}
}
}
public static void main(String[] args) {
//初始化图
Map<String,String[]> graph = new HashMap<>();
graph.put("you",new String[]{"alice","bob","claire"});
graph.put("bob",new String[]{"anuj","peggy"});
graph.put("alice",new String[]{"peggy"});
graph.put("claire",new String[]{"thom","jonny"});
graph.put("anuj",new String[]{});
graph.put("peggy",new String[]{});
graph.put("thom",new String[]{});
graph.put("jonny",new String[]{});
DFS dfs = new DFS(graph,"you");
System.out.println(dfs.dfs());
}
}